blob: acad9010eef435b29cb59dee134c7f4418be13d0 [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 Goyal2bba1902018-02-27 12:20:50 -080059import com.android.launcher3.model.ModelWriter;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070061import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070062import com.android.launcher3.provider.RestoreDbTask;
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 Goyal2bba1902018-02-27 12:20:50 -0800323 if (ModelWriter.DEBUG_DELETE) {
324 String args = selectionArgs == null ? null : TextUtils.join(",", selectionArgs);
325 FileLog.d(TAG, "Delete uri=" + uri + ", selection=" + selection
326 + ", selectionArgs=" + args, new Exception());
327 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700328 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
330
331 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332
Louis Begina9c21c62016-08-15 15:18:41 -0700333 if (Binder.getCallingPid() != Process.myPid()
334 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700335 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700336 }
337 int count = db.delete(args.table, args.where, args.args);
338 if (count > 0) {
339 notifyListeners();
340 reloadLauncherIfExternal();
341 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 return count;
343 }
344
345 @Override
346 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700347 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
349
Chris Wren1ada10d2013-09-13 18:01:38 -0400350 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
352 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700353 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354
Sunny Goyald1064182015-08-13 12:08:30 -0700355 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 return count;
357 }
358
Sunny Goyal7779d622015-06-11 16:18:39 -0700359 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700360 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700361 if (Binder.getCallingUid() != Process.myUid()) {
362 return null;
363 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700364 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700365
366 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700367 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
368 clearFlagEmptyDbCreated();
369 return null;
370 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700371 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
372 Bundle result = new Bundle();
373 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
374 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
375 return result;
376 }
Sunny Goyald2497482015-09-22 18:24:19 -0700377 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
378 Bundle result = new Bundle();
379 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
380 return result;
381 }
382 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
383 Bundle result = new Bundle();
384 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
385 return result;
386 }
387 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
388 Bundle result = new Bundle();
389 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
390 return result;
391 }
392 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800393 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700394 return null;
395 }
396 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
397 loadDefaultFavoritesIfNecessary();
398 return null;
399 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700400 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
401 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
402 return null;
403 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700404 }
405 return null;
406 }
407
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700408 /**
409 * Deletes any empty folder from the DB.
410 * @return Ids of deleted folders.
411 */
Sunny Goyald2497482015-09-22 18:24:19 -0700412 private ArrayList<Long> deleteEmptyFolders() {
413 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700414 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700415 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700416 // Select folders whose id do not match any container value.
417 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
418 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
419 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
420 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700421 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700422 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700423 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700424 selection, null, null, null, null)) {
425 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700426 }
Sunny Goyald2497482015-09-22 18:24:19 -0700427 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700428 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 LauncherSettings.Favorites._ID, folderIds), null);
430 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700431 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 } catch (SQLException ex) {
433 Log.e(TAG, ex.getMessage(), ex);
434 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700435 }
436 return folderIds;
437 }
438
Sunny Goyalf076eae2016-01-11 12:25:10 -0800439 /**
440 * Overridden in tests
441 */
442 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700443 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400444 }
445
Adam Cohen091440a2015-03-18 14:16:05 -0700446 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800448 }
449
Sunny Goyald2497482015-09-22 18:24:19 -0700450 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700451 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700452 }
453
Sunny Goyal42de82f2014-09-26 22:09:29 -0700454 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700455 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700456 * 1) From the app restrictions
457 * 2) From a package provided by play store
458 * 3) From a partner configuration APK, already in the system image
459 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700460 */
Sunny Goyald2497482015-09-22 18:24:19 -0700461 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700462 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700463
Winson Chungc763c4e2013-07-19 13:49:06 -0700464 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500465 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200466
Sunny Goyal55fddc82017-04-06 15:02:52 -0700467 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700468 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700469 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700470 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700471 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700472 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700473 final Partner partner = Partner.get(getContext().getPackageManager());
474 if (partner != null && partner.hasDefaultLayout()) {
475 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700476 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700477 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700478 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700479 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700480 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700482 }
483 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700484
Sunny Goyal9d219682014-10-23 14:21:02 -0700485 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700486 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700487 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700488 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800489
490 // There might be some partially restored DB items, due to buggy restore logic in
491 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800492 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700493 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700494 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
495 && usingExternallyProvidedLayout) {
496 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800497 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700498 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700499 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700500 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700501 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700502 }
503 }
504
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700505 /**
506 * Creates workspace loader from an XML resource listed in the app restrictions.
507 *
508 * @return the loader if the restrictions are set and the resource exists; null otherwise.
509 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700510 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700511 Context ctx = getContext();
512 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
513 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700514 if (bundle == null) {
515 return null;
516 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700517
Sunny Goyal35ca8732015-04-06 10:45:31 -0700518 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700519 if (packageName != null) {
520 try {
521 Resources targetResources = ctx.getPackageManager()
522 .getResourcesForApplication(packageName);
523 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700524 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700525 } catch (NameNotFoundException e) {
526 Log.e(TAG, "Target package for restricted profile not found", e);
527 return null;
528 }
529 }
530 return null;
531 }
532
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700533 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700534 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
535 int defaultLayout = idp.defaultLayoutId;
536
537 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
538 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
539 defaultLayout = idp.demoModeLayoutId;
540 }
541
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700542 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700543 mOpenHelper, getContext().getResources(), defaultLayout);
544 }
545
Sunny Goyald3849d12015-10-29 10:28:32 -0700546 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800547 * The class is subclassed in tests to create an in-memory db.
548 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700549 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700552 private long mMaxItemId = -1;
553 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800554
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700555 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
556 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700557 // Table creation sometimes fails silently, which leads to a crash loop.
558 // This way, we will try to create a table every time after crash, so the device
559 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700560 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700561 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
562 // This operation is a no-op if the table already exists.
563 addFavoritesTable(getWritableDatabase(), true);
564 addWorkspacesTable(getWritableDatabase(), true);
565 }
566
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700567 initIds();
568 }
569
570 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700571 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 */
573 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700574 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700575 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700576 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700577 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700578 }
579
580 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700581 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
582 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 if (mMaxItemId == -1) {
584 mMaxItemId = initializeMaxItemId(getWritableDatabase());
585 }
586 if (mMaxScreenId == -1) {
587 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700588 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589 }
590
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700591 private boolean tableExists(String tableName) {
592 Cursor c = getReadableDatabase().query(
593 true, "sqlite_master", new String[] {"tbl_name"},
594 "tbl_name = ?", new String[] {tableName},
595 null, null, null, null, null);
596 try {
597 return c.getCount() > 0;
598 } finally {
599 c.close();
600 }
601 }
602
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800603 @Override
604 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800605 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700606
Adam Cohendcd297f2013-06-18 13:13:40 -0700607 mMaxItemId = 1;
608 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700609
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700610 addFavoritesTable(db, false);
611 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800613 // Fresh and clean launcher DB.
614 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800615 onEmptyDbCreated();
616 }
617
618 /**
619 * Overriden in tests.
620 */
621 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700622 // Database was just created, so wipe any previous widgets
623 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700624 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700625 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530626 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700627 }
628
Sunny Goyalf076eae2016-01-11 12:25:10 -0800629 // Set the flag for empty DB
630 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800631 }
632
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700633 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800634 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800635 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636 }
637
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700638 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700639 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700640 }
641
642 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
643 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700644 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800645 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400646 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
647 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700648 ");");
649 }
650
Adam Cohen119285e2014-04-02 16:59:08 -0700651 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700652 // Delete items directly on the workspace who's screen id doesn't exist
653 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
654 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700655 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700656 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700657 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700658 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700659 " AND " +
660 LauncherSettings.Favorites.CONTAINER + " = " +
661 LauncherSettings.Favorites.CONTAINER_DESKTOP;
662 db.execSQL(removeOrphanedDesktopItems);
663
664 // Delete items contained in folders which no longer exist (after above statement)
665 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
666 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700667 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700668 " WHERE " +
669 LauncherSettings.Favorites.CONTAINER + " <> " +
670 LauncherSettings.Favorites.CONTAINER_DESKTOP +
671 " AND "
672 + LauncherSettings.Favorites.CONTAINER + " <> " +
673 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
674 " AND "
675 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700676 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700677 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
678 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
679 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700680 }
681
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800682 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700683 public void onOpen(SQLiteDatabase db) {
684 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700685
686 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
687 if (!schemaFile.exists()) {
688 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700689 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700690 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
691 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700692 }
693
694 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700695 * One-time data updated before support of onDowngrade was added. This update is backwards
696 * compatible and can safely be run multiple times.
697 * Note: No new logic should be added here after release, as the new logic might not get
698 * executed on an existing device.
699 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700700 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700701 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
702 // Remove "profile extra"
703 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
704 for (UserHandle user : um.getUserProfiles()) {
705 long serial = um.getSerialNumberForUser(user);
706 String sql = "update favorites set intent = replace(intent, "
707 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
708 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700709 }
710 }
711
712 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700714 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800715 switch (oldVersion) {
716 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800717 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800718 case 12: {
719 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
720 // to persist workspace screens and their relative order.
721 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700722 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800723 }
724 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700725 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800726 // Insert new column for holding widget provider name
727 db.execSQL("ALTER TABLE favorites " +
728 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700729 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800730 } catch (SQLException ex) {
731 Log.e(TAG, ex.getMessage(), ex);
732 // Old version remains, which means we wipe old data
733 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800734 }
735 }
736 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700737 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 // Insert new column for holding update timestamp
739 db.execSQL("ALTER TABLE favorites " +
740 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
741 db.execSQL("ALTER TABLE workspaceScreens " +
742 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700743 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800744 } catch (SQLException ex) {
745 Log.e(TAG, ex.getMessage(), ex);
746 // Old version remains, which means we wipe old data
747 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 }
749 }
750 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700751 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800752 // Old version remains, which means we wipe old data
753 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 }
755 }
756 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700757 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800758 }
759 case 17: {
760 // No-op
761 }
762 case 18: {
763 // Due to a data loss bug, some users may have items associated with screen ids
764 // which no longer exist. Since this can cause other problems, and since the user
765 // will never see these items anyway, we use database upgrade as an opportunity to
766 // clean things up.
767 removeOrphanedItems(db);
768 }
769 case 19: {
770 // Add userId column
771 if (!addProfileColumn(db)) {
772 // Old version remains, which means we wipe old data
773 break;
774 }
775 }
776 case 20:
777 if (!updateFolderItemsRank(db, true)) {
778 break;
779 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800780 case 21:
781 // Recreate workspace table with screen id a primary key
782 if (!recreateWorkspaceTable(db)) {
783 break;
784 }
785 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700786 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
787 // Old version remains, which means we wipe old data
788 break;
789 }
790 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700791 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700792 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700793 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000794 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700795 case 25:
796 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700797 case 26:
798 // QSB was moved to the grid. Clear the first row on screen 0.
799 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800800 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700801 break;
802 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700803 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 // DB Upgraded successfully
805 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400806 }
807
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 // DB was not upgraded
809 Log.w(TAG, "Destroying all old data.");
810 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800811 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800812
Adam Cohen9b1d0622014-05-21 19:01:57 -0700813 @Override
814 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700815 try {
816 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
817 .onDowngrade(db, oldVersion, newVersion);
818 } catch (Exception e) {
819 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
820 ". Wiping databse.", e);
821 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700822 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700823 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700824
Sunny Goyal42de82f2014-09-26 22:09:29 -0700825 /**
826 * Clears all the data for a fresh start.
827 */
828 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700829 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800830 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
831 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
832 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700833 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800834 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700835 }
836
Sunny Goyald2f38192015-02-25 10:46:34 -0800837 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700838 * Removes widgets which are registered to the Launcher's host, but are not present
839 * in our model.
840 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700841 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700842 public void removeGhostWidgets(SQLiteDatabase db) {
843 // Get all existing widget ids.
844 final AppWidgetHost host = newLauncherWidgetHost();
845 final int[] allWidgets;
846 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700847 // Although the method was defined in O, it has existed since the beginning of time,
848 // so it might work on older platforms as well.
849 allWidgets = host.getAppWidgetIds();
850 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700851 Log.e(TAG, "getAppWidgetIds not supported", e);
852 return;
853 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700854 final HashSet<Integer> validWidgets = new HashSet<>();
855 try (Cursor c = db.query(Favorites.TABLE_NAME,
856 new String[] {Favorites.APPWIDGET_ID },
857 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700858 while (c.moveToNext()) {
859 validWidgets.add(c.getInt(0));
860 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700861 } catch (SQLException ex) {
862 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700863 return;
864 }
865 for (int widgetId : allWidgets) {
866 if (!validWidgets.contains(widgetId)) {
867 try {
868 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
869 host.deleteAppWidgetId(widgetId);
870 } catch (RuntimeException e) {
871 // Ignore
872 }
873 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700874 }
875 }
876
877 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700878 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
879 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
880 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700881 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700882 try (SQLiteTransaction t = new SQLiteTransaction(db);
883 // Only consider the primary user as other users can't have a shortcut.
884 Cursor c = db.query(Favorites.TABLE_NAME,
885 new String[] { Favorites._ID, Favorites.INTENT},
886 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
887 " AND profileId=" + getDefaultUserSerial(),
888 null, null, null, null);
889 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
890 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
891 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700892 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
893 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
894
895 while (c.moveToNext()) {
896 String intentDescription = c.getString(intentIndex);
897 Intent intent;
898 try {
899 intent = Intent.parseUri(intentDescription, 0);
900 } catch (URISyntaxException e) {
901 Log.e(TAG, "Unable to parse intent", e);
902 continue;
903 }
904
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700905 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700906 continue;
907 }
908
909 long id = c.getLong(idIndex);
910 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700911 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700912 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700913 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700914 } catch (SQLException ex) {
915 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700916 }
917 }
918
919 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800920 * Recreates workspace table and migrates data to the new table.
921 */
922 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700923 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
924 final ArrayList<Long> sortedIDs;
925
926 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800927 new String[] {LauncherSettings.WorkspaceScreens._ID},
928 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700929 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
930 // Use LinkedHashSet so that ordering is preserved
931 sortedIDs = new ArrayList<>(
932 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800933 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700934 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700935 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800936
937 // Add all screen ids back
938 int total = sortedIDs.size();
939 for (int i = 0; i < total; i++) {
940 ContentValues values = new ContentValues();
941 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
942 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
943 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700944 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800945 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700946 t.commit();
947 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800948 } catch (SQLException ex) {
949 // Old version remains, which means we wipe old data
950 Log.e(TAG, ex.getMessage(), ex);
951 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800952 }
953 return true;
954 }
955
Adam Cohen091440a2015-03-18 14:16:05 -0700956 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700957 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800958 if (addRankColumn) {
959 // Insert new column for holding rank
960 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
961 }
962
963 // Get a map for folder ID to folder width
964 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
965 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
966 + " GROUP BY container;",
967 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
968
969 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800970 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
971 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800972 new Object[] {c.getLong(1) + 1, c.getLong(0)});
973 }
974
975 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700976 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800977 } catch (SQLException ex) {
978 // Old version remains, which means we wipe old data
979 Log.e(TAG, ex.getMessage(), ex);
980 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800981 }
982 return true;
983 }
984
Kenny Guyed131872014-04-30 03:02:21 +0100985 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700986 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700987 }
988
989 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700990 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700991 db.execSQL("ALTER TABLE favorites ADD COLUMN "
992 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700993 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100994 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100995 Log.e(TAG, ex.getMessage(), ex);
996 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100997 }
998 return true;
999 }
1000
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 // Generates a new ID to use for an object in your database. This method should be only
1002 // called from the main UI thread. As an exception, we do call it when we call the
1003 // constructor from the worker thread; however, this doesn't extend until after the
1004 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1005 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001006 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 public long generateNewItemId() {
1008 if (mMaxItemId < 0) {
1009 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001010 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 mMaxItemId += 1;
1012 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 }
1014
Sunny Goyal55fddc82017-04-06 15:02:52 -07001015 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001016 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001017 }
1018
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001019 @Override
1020 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001021 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001022 }
1023
Chris Wren5dee7af2013-12-20 17:22:11 -05001024 public void checkId(String table, ContentValues values) {
1025 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001026 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001027 mMaxScreenId = Math.max(id, mMaxScreenId);
1028 } else {
1029 mMaxItemId = Math.max(id, mMaxItemId);
1030 }
1031 }
1032
Adam Cohendcd297f2013-06-18 13:13:40 -07001033 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001034 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001035 }
1036
1037 // Generates a new ID to use for an workspace screen in your database. This method
1038 // should be only called from the main UI thread. As an exception, we do call it when we
1039 // call the constructor from the worker thread; however, this doesn't extend until after the
1040 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1041 // after that point
1042 public long generateNewScreenId() {
1043 if (mMaxScreenId < 0) {
1044 throw new RuntimeException("Error: max screen id was not initialized");
1045 }
1046 mMaxScreenId += 1;
1047 return mMaxScreenId;
1048 }
1049
Adam Cohendcd297f2013-06-18 13:13:40 -07001050 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001051 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001052 }
1053
Adam Cohen091440a2015-03-18 14:16:05 -07001054 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001055 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001056 // TODO: Use multiple loaders with fall-back and transaction.
1057 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001058
1059 // Add the screens specified by the items above
1060 Collections.sort(screenIds);
1061 int rank = 0;
1062 ContentValues values = new ContentValues();
1063 for (Long id : screenIds) {
1064 values.clear();
1065 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1066 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001067 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001068 throw new RuntimeException("Failed initialize screen table"
1069 + "from default layout");
1070 }
1071 rank++;
1072 }
1073
1074 // Ensure that the max ids are initialized
1075 mMaxItemId = initializeMaxItemId(db);
1076 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001077
Adam Cohen71483f42014-05-15 14:04:01 -07001078 return count;
1079 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001080 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001081
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001082 /**
1083 * @return the max _id in the provided table.
1084 */
Adam Cohen091440a2015-03-18 14:16:05 -07001085 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001086 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1087 // get the result
1088 long id = -1;
1089 if (c != null && c.moveToNext()) {
1090 id = c.getLong(0);
1091 }
1092 if (c != null) {
1093 c.close();
1094 }
1095
1096 if (id == -1) {
1097 throw new RuntimeException("Error: could not query max id in " + table);
1098 }
1099
1100 return id;
1101 }
1102
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001103 static class SqlArguments {
1104 public final String table;
1105 public final String where;
1106 public final String[] args;
1107
1108 SqlArguments(Uri url, String where, String[] args) {
1109 if (url.getPathSegments().size() == 1) {
1110 this.table = url.getPathSegments().get(0);
1111 this.where = where;
1112 this.args = args;
1113 } else if (url.getPathSegments().size() != 2) {
1114 throw new IllegalArgumentException("Invalid URI: " + url);
1115 } else if (!TextUtils.isEmpty(where)) {
1116 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1117 } else {
1118 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001119 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001120 this.args = null;
1121 }
1122 }
1123
1124 SqlArguments(Uri url) {
1125 if (url.getPathSegments().size() == 1) {
1126 table = url.getPathSegments().get(0);
1127 where = null;
1128 args = null;
1129 } else {
1130 throw new IllegalArgumentException("Invalid URI: " + url);
1131 }
1132 }
1133 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001134
1135 private static class ChangeListenerWrapper implements Handler.Callback {
1136
1137 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001138 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001139
1140 private LauncherProviderChangeListener mListener;
1141
1142 @Override
1143 public boolean handleMessage(Message msg) {
1144 if (mListener != null) {
1145 switch (msg.what) {
1146 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001147 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001148 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001149 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001150 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001151 break;
1152 }
1153 }
1154 return true;
1155 }
1156 }
Adam Cohen72960972014-01-15 18:13:55 -08001157}