blob: 25a698b1593aad6cbe3575146ebfc7dd09972a53 [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 Goyale26d1002016-06-20 14:52:14 -070047import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080048import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070049import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070052
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
54import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070055import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070057import com.android.launcher3.config.FeatureFlags;
Sunny Goyalca187462017-03-31 20:09:34 -070058import com.android.launcher3.graphics.IconShapeOverride;
Sunny Goyalfdbef272017-02-01 12:52:54 -080059import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070060import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070061import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070062import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070063import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070064import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070065import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070066import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070067import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070068
Sunny Goyal05f30882017-05-03 12:42:18 -070069import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080070import java.io.FileDescriptor;
71import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070072import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070073import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070074import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070075import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070076import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070079 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080080 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
Sunny Goyal05f30882017-05-03 12:42:18 -070082 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
83
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070084 /**
85 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
86 */
Sunny Goyal05f30882017-05-03 12:42:18 -070087 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Sunny Goyal3d706ad2017-03-06 16:56:39 -080089 public static final String AUTHORITY = (BuildConfig.APPLICATION_ID + ".settings").intern();
Winson Chung3d503fb2011-07-13 17:25:49 -070090
Sunny Goyale87e6ab2014-11-21 22:42:53 -080091 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070093 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
94
Sunny Goyalb5b55c82016-05-10 12:28:59 -070095 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
96 private Handler mListenerHandler;
97
Sunny Goyalf076eae2016-01-11 12:25:10 -080098 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800100 /**
101 * $ adb shell dumpsys activity provider com.android.launcher3
102 */
103 @Override
104 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
105 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
106 if (appState == null || !appState.getModel().isModelLoaded()) {
107 return;
108 }
109 appState.getModel().dumpState("", fd, writer, args);
110 }
111
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112 @Override
113 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800114 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700115 Log.d(TAG, "Launcher process started");
116 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700117 mListenerHandler = new Handler(mListenerWrapper);
118
Sunny Goyalfdbef272017-02-01 12:52:54 -0800119 // The content provider exists for the entire duration of the launcher main process and
120 // is the first component to get created. Initializing FileLog here ensures that it's
121 // always available in the main process.
122 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700123 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700124 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 return true;
126 }
127
Sunny Goyald3849d12015-10-29 10:28:32 -0700128 /**
129 * Sets a provider listener.
130 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700131 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700132 Preconditions.assertUIThread();
133 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700134 }
135
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136 @Override
137 public String getType(Uri uri) {
138 SqlArguments args = new SqlArguments(uri, null, null);
139 if (TextUtils.isEmpty(args.where)) {
140 return "vnd.android.cursor.dir/" + args.table;
141 } else {
142 return "vnd.android.cursor.item/" + args.table;
143 }
144 }
145
Sunny Goyalf076eae2016-01-11 12:25:10 -0800146 /**
147 * Overridden in tests
148 */
149 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700150 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700151 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700152
153 if (RestoreDbTask.isPending(getContext())) {
154 if (!RestoreDbTask.performRestore(mOpenHelper)) {
155 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
156 }
157 // Set is pending to false irrespective of the result, so that it doesn't get
158 // executed again.
159 RestoreDbTask.setPending(getContext(), false);
160 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700161 }
162 }
163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 @Override
165 public Cursor query(Uri uri, String[] projection, String selection,
166 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700167 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168
169 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
170 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
171 qb.setTables(args.table);
172
Romain Guy73b979d2009-06-09 12:57:21 -0700173 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
175 result.setNotificationUri(getContext().getContentResolver(), uri);
176
177 return result;
178 }
179
Adam Cohen091440a2015-03-18 14:16:05 -0700180 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500182 if (values == null) {
183 throw new RuntimeException("Error: attempting to insert null values");
184 }
Adam Cohen71483f42014-05-15 14:04:01 -0700185 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700186 throw new RuntimeException("Error: attempting to add item without specifying an id");
187 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500188 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700189 return db.insert(table, nullColumnHack, values);
190 }
191
Sunny Goyald1064182015-08-13 12:08:30 -0700192 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700193 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700194 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
195 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800196 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700197 }
198 }
199 }
200
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 @Override
202 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700203 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204 SqlArguments args = new SqlArguments(uri);
205
Sunny Goyald1064182015-08-13 12:08:30 -0700206 // In very limited cases, we support system|signature permission apps to modify the db.
207 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700208 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700209 return null;
210 }
211 }
212
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400214 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700215 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800216 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217
218 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700219 notifyListeners();
220
Sunny Goyalc74e4192015-09-08 14:01:03 -0700221 if (Utilities.ATLEAST_MARSHMALLOW) {
222 reloadLauncherIfExternal();
223 } else {
224 // Deprecated behavior to support legacy devices which rely on provider callbacks.
225 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
226 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800227 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700228 }
229
230 String notify = uri.getQueryParameter("notify");
231 if (notify == null || "true".equals(notify)) {
232 getContext().getContentResolver().notifyChange(uri, null);
233 }
234 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 return uri;
236 }
237
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700238 private boolean initializeExternalAdd(ContentValues values) {
239 // 1. Ensure that externally added items have a valid item id
240 long id = mOpenHelper.generateNewItemId();
241 values.put(LauncherSettings.Favorites._ID, id);
242
243 // 2. In the case of an app widget, and if no app widget id is specified, we
244 // attempt allocate and bind the widget.
245 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
246 if (itemType != null &&
247 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
248 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
249
250 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
251 ComponentName cn = ComponentName.unflattenFromString(
252 values.getAsString(Favorites.APPWIDGET_PROVIDER));
253
254 if (cn != null) {
255 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
257 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700258 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
259 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700260 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700261 return false;
262 }
263 } catch (RuntimeException e) {
264 Log.e(TAG, "Failed to initialize external widget", e);
265 return false;
266 }
267 } else {
268 return false;
269 }
270 }
271
272 // Add screen id if not present
273 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
274 SQLiteStatement stmp = null;
275 try {
276 stmp = mOpenHelper.getWritableDatabase().compileStatement(
277 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
278 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
279 stmp.bindLong(1, screenId);
280
281 ContentValues valuesInserted = new ContentValues();
282 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
283 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
284 return true;
285 } catch (Exception e) {
286 return false;
287 } finally {
288 Utilities.closeSilently(stmp);
289 }
290 }
291
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 @Override
293 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700294 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 SqlArguments args = new SqlArguments(uri);
296
297 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700298 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 int numValues = values.length;
300 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400301 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700302 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
303 return 0;
304 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700306 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 }
308
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700309 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700310 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800311 return values.length;
312 }
313
314 @Override
Yura085c8532014-02-11 15:15:29 +0000315 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
316 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700317 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700318 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000319 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700320 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700321 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000322 return result;
Yura085c8532014-02-11 15:15:29 +0000323 }
324 }
325
326 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 public int delete(Uri uri, String selection, String[] selectionArgs) {
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 Goyale2fba6c2015-05-12 10:39:59 -0700631
632 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800633 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800634 mContext);
635 }
636
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700637 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800638 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800639 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 }
641
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700642 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700643 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700644 }
645
646 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
647 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700648 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800649 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400650 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
651 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700652 ");");
653 }
654
Adam Cohen119285e2014-04-02 16:59:08 -0700655 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700656 // Delete items directly on the workspace who's screen id doesn't exist
657 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
658 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700659 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700660 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700661 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700662 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700663 " AND " +
664 LauncherSettings.Favorites.CONTAINER + " = " +
665 LauncherSettings.Favorites.CONTAINER_DESKTOP;
666 db.execSQL(removeOrphanedDesktopItems);
667
668 // Delete items contained in folders which no longer exist (after above statement)
669 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
670 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700671 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700672 " WHERE " +
673 LauncherSettings.Favorites.CONTAINER + " <> " +
674 LauncherSettings.Favorites.CONTAINER_DESKTOP +
675 " AND "
676 + LauncherSettings.Favorites.CONTAINER + " <> " +
677 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
678 " AND "
679 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700680 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700681 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
682 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
683 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700684 }
685
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700687 public void onOpen(SQLiteDatabase db) {
688 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700689
690 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
691 if (!schemaFile.exists()) {
692 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700693 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700694 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
695 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700696 }
697
698 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700699 * One-time data updated before support of onDowngrade was added. This update is backwards
700 * compatible and can safely be run multiple times.
701 * Note: No new logic should be added here after release, as the new logic might not get
702 * executed on an existing device.
703 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700704 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700705 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
706 // Remove "profile extra"
707 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
708 for (UserHandle user : um.getUserProfiles()) {
709 long serial = um.getSerialNumberForUser(user);
710 String sql = "update favorites set intent = replace(intent, "
711 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
712 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700713 }
714 }
715
716 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800717 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700718 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800719 switch (oldVersion) {
720 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800721 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800722 case 12: {
723 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
724 // to persist workspace screens and their relative order.
725 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700726 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 }
728 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700729 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800730 // Insert new column for holding widget provider name
731 db.execSQL("ALTER TABLE favorites " +
732 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700733 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800734 } catch (SQLException ex) {
735 Log.e(TAG, ex.getMessage(), ex);
736 // Old version remains, which means we wipe old data
737 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 }
739 }
740 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700741 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 // Insert new column for holding update timestamp
743 db.execSQL("ALTER TABLE favorites " +
744 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
745 db.execSQL("ALTER TABLE workspaceScreens " +
746 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700747 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 } catch (SQLException ex) {
749 Log.e(TAG, ex.getMessage(), ex);
750 // Old version remains, which means we wipe old data
751 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800752 }
753 }
754 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700755 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800756 // Old version remains, which means we wipe old data
757 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800758 }
759 }
760 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700761 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800762 }
763 case 17: {
764 // No-op
765 }
766 case 18: {
767 // Due to a data loss bug, some users may have items associated with screen ids
768 // which no longer exist. Since this can cause other problems, and since the user
769 // will never see these items anyway, we use database upgrade as an opportunity to
770 // clean things up.
771 removeOrphanedItems(db);
772 }
773 case 19: {
774 // Add userId column
775 if (!addProfileColumn(db)) {
776 // Old version remains, which means we wipe old data
777 break;
778 }
779 }
780 case 20:
781 if (!updateFolderItemsRank(db, true)) {
782 break;
783 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800784 case 21:
785 // Recreate workspace table with screen id a primary key
786 if (!recreateWorkspaceTable(db)) {
787 break;
788 }
789 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700790 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
791 // Old version remains, which means we wipe old data
792 break;
793 }
794 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700795 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700796 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700797 case 24:
798 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700799 case 25:
800 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700801 case 26:
802 // QSB was moved to the grid. Clear the first row on screen 0.
803 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800804 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700805 break;
806 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700807 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 // DB Upgraded successfully
809 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400810 }
811
Sunny Goyala2cc6242015-01-14 14:23:02 -0800812 // DB was not upgraded
813 Log.w(TAG, "Destroying all old data.");
814 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800815 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800816
Adam Cohen9b1d0622014-05-21 19:01:57 -0700817 @Override
818 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700819 try {
820 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
821 .onDowngrade(db, oldVersion, newVersion);
822 } catch (Exception e) {
823 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
824 ". Wiping databse.", e);
825 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700826 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700827 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700828
Sunny Goyal42de82f2014-09-26 22:09:29 -0700829 /**
830 * Clears all the data for a fresh start.
831 */
832 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700833 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800834 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
835 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
836 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700837 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800838 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700839 }
840
Sunny Goyald2f38192015-02-25 10:46:34 -0800841 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700842 * Removes widgets which are registered to the Launcher's host, but are not present
843 * in our model.
844 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700845 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700846 public void removeGhostWidgets(SQLiteDatabase db) {
847 // Get all existing widget ids.
848 final AppWidgetHost host = newLauncherWidgetHost();
849 final int[] allWidgets;
850 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700851 // Although the method was defined in O, it has existed since the beginning of time,
852 // so it might work on older platforms as well.
853 allWidgets = host.getAppWidgetIds();
854 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700855 Log.e(TAG, "getAppWidgetIds not supported", e);
856 return;
857 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700858 final HashSet<Integer> validWidgets = new HashSet<>();
859 try (Cursor c = db.query(Favorites.TABLE_NAME,
860 new String[] {Favorites.APPWIDGET_ID },
861 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700862 while (c.moveToNext()) {
863 validWidgets.add(c.getInt(0));
864 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700865 } catch (SQLException ex) {
866 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700867 return;
868 }
869 for (int widgetId : allWidgets) {
870 if (!validWidgets.contains(widgetId)) {
871 try {
872 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
873 host.deleteAppWidgetId(widgetId);
874 } catch (RuntimeException e) {
875 // Ignore
876 }
877 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700878 }
879 }
880
881 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700882 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
883 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
884 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700885 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700886 try (SQLiteTransaction t = new SQLiteTransaction(db);
887 // Only consider the primary user as other users can't have a shortcut.
888 Cursor c = db.query(Favorites.TABLE_NAME,
889 new String[] { Favorites._ID, Favorites.INTENT},
890 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
891 " AND profileId=" + getDefaultUserSerial(),
892 null, null, null, null);
893 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
894 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
895 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700896 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
897 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
898
899 while (c.moveToNext()) {
900 String intentDescription = c.getString(intentIndex);
901 Intent intent;
902 try {
903 intent = Intent.parseUri(intentDescription, 0);
904 } catch (URISyntaxException e) {
905 Log.e(TAG, "Unable to parse intent", e);
906 continue;
907 }
908
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700909 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700910 continue;
911 }
912
913 long id = c.getLong(idIndex);
914 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700915 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700916 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700917 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700918 } catch (SQLException ex) {
919 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700920 }
921 }
922
923 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800924 * Recreates workspace table and migrates data to the new table.
925 */
926 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700927 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
928 final ArrayList<Long> sortedIDs;
929
930 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800931 new String[] {LauncherSettings.WorkspaceScreens._ID},
932 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700933 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
934 // Use LinkedHashSet so that ordering is preserved
935 sortedIDs = new ArrayList<>(
936 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800937 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700938 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700939 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800940
941 // Add all screen ids back
942 int total = sortedIDs.size();
943 for (int i = 0; i < total; i++) {
944 ContentValues values = new ContentValues();
945 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
946 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
947 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700948 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800949 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700950 t.commit();
951 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800952 } catch (SQLException ex) {
953 // Old version remains, which means we wipe old data
954 Log.e(TAG, ex.getMessage(), ex);
955 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800956 }
957 return true;
958 }
959
Adam Cohen091440a2015-03-18 14:16:05 -0700960 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700961 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800962 if (addRankColumn) {
963 // Insert new column for holding rank
964 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
965 }
966
967 // Get a map for folder ID to folder width
968 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
969 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
970 + " GROUP BY container;",
971 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
972
973 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800974 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
975 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800976 new Object[] {c.getLong(1) + 1, c.getLong(0)});
977 }
978
979 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700980 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800981 } catch (SQLException ex) {
982 // Old version remains, which means we wipe old data
983 Log.e(TAG, ex.getMessage(), ex);
984 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800985 }
986 return true;
987 }
988
Kenny Guyed131872014-04-30 03:02:21 +0100989 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700990 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700991 }
992
993 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700994 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700995 db.execSQL("ALTER TABLE favorites ADD COLUMN "
996 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700997 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100998 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100999 Log.e(TAG, ex.getMessage(), ex);
1000 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001001 }
1002 return true;
1003 }
1004
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001005 // Generates a new ID to use for an object in your database. This method should be only
1006 // called from the main UI thread. As an exception, we do call it when we call the
1007 // constructor from the worker thread; however, this doesn't extend until after the
1008 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1009 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001010 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 public long generateNewItemId() {
1012 if (mMaxItemId < 0) {
1013 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001014 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001015 mMaxItemId += 1;
1016 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 }
1018
Sunny Goyal55fddc82017-04-06 15:02:52 -07001019 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001020 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001021 }
1022
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001023 @Override
1024 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001025 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001026 }
1027
Chris Wren5dee7af2013-12-20 17:22:11 -05001028 public void checkId(String table, ContentValues values) {
1029 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001030 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001031 mMaxScreenId = Math.max(id, mMaxScreenId);
1032 } else {
1033 mMaxItemId = Math.max(id, mMaxItemId);
1034 }
1035 }
1036
Adam Cohendcd297f2013-06-18 13:13:40 -07001037 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001038 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001039 }
1040
1041 // Generates a new ID to use for an workspace screen in your database. This method
1042 // should be only called from the main UI thread. As an exception, we do call it when we
1043 // call the constructor from the worker thread; however, this doesn't extend until after the
1044 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1045 // after that point
1046 public long generateNewScreenId() {
1047 if (mMaxScreenId < 0) {
1048 throw new RuntimeException("Error: max screen id was not initialized");
1049 }
1050 mMaxScreenId += 1;
1051 return mMaxScreenId;
1052 }
1053
Adam Cohendcd297f2013-06-18 13:13:40 -07001054 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001055 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001056 }
1057
Adam Cohen091440a2015-03-18 14:16:05 -07001058 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001059 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001060 // TODO: Use multiple loaders with fall-back and transaction.
1061 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001062
1063 // Add the screens specified by the items above
1064 Collections.sort(screenIds);
1065 int rank = 0;
1066 ContentValues values = new ContentValues();
1067 for (Long id : screenIds) {
1068 values.clear();
1069 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1070 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001071 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001072 throw new RuntimeException("Failed initialize screen table"
1073 + "from default layout");
1074 }
1075 rank++;
1076 }
1077
1078 // Ensure that the max ids are initialized
1079 mMaxItemId = initializeMaxItemId(db);
1080 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001081
Adam Cohen71483f42014-05-15 14:04:01 -07001082 return count;
1083 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001084 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001085
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001086 /**
1087 * @return the max _id in the provided table.
1088 */
Adam Cohen091440a2015-03-18 14:16:05 -07001089 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001090 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1091 // get the result
1092 long id = -1;
1093 if (c != null && c.moveToNext()) {
1094 id = c.getLong(0);
1095 }
1096 if (c != null) {
1097 c.close();
1098 }
1099
1100 if (id == -1) {
1101 throw new RuntimeException("Error: could not query max id in " + table);
1102 }
1103
1104 return id;
1105 }
1106
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001107 static class SqlArguments {
1108 public final String table;
1109 public final String where;
1110 public final String[] args;
1111
1112 SqlArguments(Uri url, String where, String[] args) {
1113 if (url.getPathSegments().size() == 1) {
1114 this.table = url.getPathSegments().get(0);
1115 this.where = where;
1116 this.args = args;
1117 } else if (url.getPathSegments().size() != 2) {
1118 throw new IllegalArgumentException("Invalid URI: " + url);
1119 } else if (!TextUtils.isEmpty(where)) {
1120 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1121 } else {
1122 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001123 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001124 this.args = null;
1125 }
1126 }
1127
1128 SqlArguments(Uri url) {
1129 if (url.getPathSegments().size() == 1) {
1130 table = url.getPathSegments().get(0);
1131 where = null;
1132 args = null;
1133 } else {
1134 throw new IllegalArgumentException("Invalid URI: " + url);
1135 }
1136 }
1137 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001138
1139 private static class ChangeListenerWrapper implements Handler.Callback {
1140
1141 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001142 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001143
1144 private LauncherProviderChangeListener mListener;
1145
1146 @Override
1147 public boolean handleMessage(Message msg) {
1148 if (mListener != null) {
1149 switch (msg.what) {
1150 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001151 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001152 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001153 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001154 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001155 break;
1156 }
1157 }
1158 return true;
1159 }
1160 }
Adam Cohen72960972014-01-15 18:13:55 -08001161}