blob: 053dc356eb026a1dd310ec302c189bfd3f272dab [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 Goyale2fba6c2015-05-12 10:39:59 -070063import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070064import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070065import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070066import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070067
Sunny Goyal05f30882017-05-03 12:42:18 -070068import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070071import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070072import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070073import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070074import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070075import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070078 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080079 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyal05f30882017-05-03 12:42:18 -070081 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
82
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070083 /**
84 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
85 */
Sunny Goyal05f30882017-05-03 12:42:18 -070086 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Sunny Goyal85525172017-11-06 13:00:42 -080088 public static final String AUTHORITY = FeatureFlags.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070089
Sunny Goyale87e6ab2014-11-21 22:42:53 -080090 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070092 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
93
Sunny Goyalb5b55c82016-05-10 12:28:59 -070094 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
95 private Handler mListenerHandler;
96
Sunny Goyalf076eae2016-01-11 12:25:10 -080097 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Hyunyoung Song6aa37292017-02-06 10:46:24 -080099 /**
100 * $ adb shell dumpsys activity provider com.android.launcher3
101 */
102 @Override
103 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
104 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
105 if (appState == null || !appState.getModel().isModelLoaded()) {
106 return;
107 }
108 appState.getModel().dumpState("", fd, writer, args);
109 }
110
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111 @Override
112 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800113 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700114 Log.d(TAG, "Launcher process started");
115 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700116 mListenerHandler = new Handler(mListenerWrapper);
117
Sunny Goyalfdbef272017-02-01 12:52:54 -0800118 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800119 // is the first component to get created.
120 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 return true;
122 }
123
Sunny Goyald3849d12015-10-29 10:28:32 -0700124 /**
125 * Sets a provider listener.
126 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700127 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700128 Preconditions.assertUIThread();
129 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700130 }
131
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 @Override
133 public String getType(Uri uri) {
134 SqlArguments args = new SqlArguments(uri, null, null);
135 if (TextUtils.isEmpty(args.where)) {
136 return "vnd.android.cursor.dir/" + args.table;
137 } else {
138 return "vnd.android.cursor.item/" + args.table;
139 }
140 }
141
Sunny Goyalf076eae2016-01-11 12:25:10 -0800142 /**
143 * Overridden in tests
144 */
145 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700146 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700147 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700148
149 if (RestoreDbTask.isPending(getContext())) {
150 if (!RestoreDbTask.performRestore(mOpenHelper)) {
151 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
152 }
153 // Set is pending to false irrespective of the result, so that it doesn't get
154 // executed again.
155 RestoreDbTask.setPending(getContext(), false);
156 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Cursor query(Uri uri, String[] projection, String selection,
162 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
166 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
167 qb.setTables(args.table);
168
Romain Guy73b979d2009-06-09 12:57:21 -0700169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
171 result.setNotificationUri(getContext().getContentResolver(), uri);
172
173 return result;
174 }
175
Adam Cohen091440a2015-03-18 14:16:05 -0700176 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500178 if (values == null) {
179 throw new RuntimeException("Error: attempting to insert null values");
180 }
Adam Cohen71483f42014-05-15 14:04:01 -0700181 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 throw new RuntimeException("Error: attempting to add item without specifying an id");
183 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500184 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700185 return db.insert(table, nullColumnHack, values);
186 }
187
Sunny Goyald1064182015-08-13 12:08:30 -0700188 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700189 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700190 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
191 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800192 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700193 }
194 }
195 }
196
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 @Override
198 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700199 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 SqlArguments args = new SqlArguments(uri);
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 // In very limited cases, we support system|signature permission apps to modify the db.
203 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700204 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700205 return null;
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700211 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800212 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
214 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700215 notifyListeners();
216
Sunny Goyalc74e4192015-09-08 14:01:03 -0700217 if (Utilities.ATLEAST_MARSHMALLOW) {
218 reloadLauncherIfExternal();
219 } else {
220 // Deprecated behavior to support legacy devices which rely on provider callbacks.
221 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
222 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800223 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700224 }
225
226 String notify = uri.getQueryParameter("notify");
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
230 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 return uri;
232 }
233
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700234 private boolean initializeExternalAdd(ContentValues values) {
235 // 1. Ensure that externally added items have a valid item id
236 long id = mOpenHelper.generateNewItemId();
237 values.put(LauncherSettings.Favorites._ID, id);
238
239 // 2. In the case of an app widget, and if no app widget id is specified, we
240 // attempt allocate and bind the widget.
241 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
242 if (itemType != null &&
243 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
244 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
245
246 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
247 ComponentName cn = ComponentName.unflattenFromString(
248 values.getAsString(Favorites.APPWIDGET_PROVIDER));
249
250 if (cn != null) {
251 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700252 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
253 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700254 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
255 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700257 return false;
258 }
259 } catch (RuntimeException e) {
260 Log.e(TAG, "Failed to initialize external widget", e);
261 return false;
262 }
263 } else {
264 return false;
265 }
266 }
267
268 // Add screen id if not present
269 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
270 SQLiteStatement stmp = null;
271 try {
272 stmp = mOpenHelper.getWritableDatabase().compileStatement(
273 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
274 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
275 stmp.bindLong(1, screenId);
276
277 ContentValues valuesInserted = new ContentValues();
278 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
279 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
280 return true;
281 } catch (Exception e) {
282 return false;
283 } finally {
284 Utilities.closeSilently(stmp);
285 }
286 }
287
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 @Override
289 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700290 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 SqlArguments args = new SqlArguments(uri);
292
293 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700294 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 int numValues = values.length;
296 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400297 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700298 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
299 return 0;
300 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700302 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 }
304
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700305 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700306 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 return values.length;
308 }
309
310 @Override
Yura085c8532014-02-11 15:15:29 +0000311 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
312 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700313 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700314 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000315 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700316 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700317 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000318 return result;
Yura085c8532014-02-11 15:15:29 +0000319 }
320 }
321
322 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800323 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyal2bba1902018-02-27 12:20:50 -0800324 if (ModelWriter.DEBUG_DELETE) {
325 String args = selectionArgs == null ? null : TextUtils.join(",", selectionArgs);
326 FileLog.d(TAG, "Delete uri=" + uri + ", selection=" + selection
327 + ", selectionArgs=" + args, new Exception());
328 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700329 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
331
332 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333
Louis Begina9c21c62016-08-15 15:18:41 -0700334 if (Binder.getCallingPid() != Process.myPid()
335 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700336 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700337 }
338 int count = db.delete(args.table, args.where, args.args);
339 if (count > 0) {
340 notifyListeners();
341 reloadLauncherIfExternal();
342 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343 return count;
344 }
345
346 @Override
347 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700348 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
350
Chris Wren1ada10d2013-09-13 18:01:38 -0400351 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
353 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700354 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355
Sunny Goyald1064182015-08-13 12:08:30 -0700356 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 return count;
358 }
359
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700361 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 if (Binder.getCallingUid() != Process.myUid()) {
363 return null;
364 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700365 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700366
367 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700368 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
369 clearFlagEmptyDbCreated();
370 return null;
371 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700372 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
373 Bundle result = new Bundle();
374 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
375 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
376 return result;
377 }
Sunny Goyald2497482015-09-22 18:24:19 -0700378 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
379 Bundle result = new Bundle();
380 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
381 return result;
382 }
383 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
384 Bundle result = new Bundle();
385 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
386 return result;
387 }
388 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
389 Bundle result = new Bundle();
390 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
391 return result;
392 }
393 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800394 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700395 return null;
396 }
397 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
398 loadDefaultFavoritesIfNecessary();
399 return null;
400 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700401 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
402 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
403 return null;
404 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700405 }
406 return null;
407 }
408
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700409 /**
410 * Deletes any empty folder from the DB.
411 * @return Ids of deleted folders.
412 */
Sunny Goyald2497482015-09-22 18:24:19 -0700413 private ArrayList<Long> deleteEmptyFolders() {
414 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700415 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700416 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700417 // Select folders whose id do not match any container value.
418 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
419 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
420 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
421 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700422 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700423 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700424 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700425 selection, null, null, null, null)) {
426 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700427 }
Sunny Goyald2497482015-09-22 18:24:19 -0700428 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700429 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700430 LauncherSettings.Favorites._ID, folderIds), null);
431 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700432 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700433 } catch (SQLException ex) {
434 Log.e(TAG, ex.getMessage(), ex);
435 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700436 }
437 return folderIds;
438 }
439
Sunny Goyalf076eae2016-01-11 12:25:10 -0800440 /**
441 * Overridden in tests
442 */
443 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700444 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400445 }
446
Adam Cohen091440a2015-03-18 14:16:05 -0700447 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800449 }
450
Sunny Goyald2497482015-09-22 18:24:19 -0700451 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700452 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700453 }
454
Sunny Goyal42de82f2014-09-26 22:09:29 -0700455 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700456 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700457 * 1) From the app restrictions
458 * 2) From a package provided by play store
459 * 3) From a partner configuration APK, already in the system image
460 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700461 */
Sunny Goyald2497482015-09-22 18:24:19 -0700462 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700463 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700464
Winson Chungc763c4e2013-07-19 13:49:06 -0700465 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500466 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200467
Sunny Goyal55fddc82017-04-06 15:02:52 -0700468 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700469 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700470 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700471 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700472 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700474 final Partner partner = Partner.get(getContext().getPackageManager());
475 if (partner != null && partner.hasDefaultLayout()) {
476 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700477 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700478 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700480 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700481 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700482 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700483 }
484 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700485
Sunny Goyal9d219682014-10-23 14:21:02 -0700486 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700487 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700489 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800490
491 // There might be some partially restored DB items, due to buggy restore logic in
492 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800493 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700494 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
496 && usingExternallyProvidedLayout) {
497 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800498 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700499 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700500 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700501 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700502 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700503 }
504 }
505
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700506 /**
507 * Creates workspace loader from an XML resource listed in the app restrictions.
508 *
509 * @return the loader if the restrictions are set and the resource exists; null otherwise.
510 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700511 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512 Context ctx = getContext();
513 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
514 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700515 if (bundle == null) {
516 return null;
517 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700518
Sunny Goyal35ca8732015-04-06 10:45:31 -0700519 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 if (packageName != null) {
521 try {
522 Resources targetResources = ctx.getPackageManager()
523 .getResourcesForApplication(packageName);
524 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700525 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526 } catch (NameNotFoundException e) {
527 Log.e(TAG, "Target package for restricted profile not found", e);
528 return null;
529 }
530 }
531 return null;
532 }
533
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700535 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
536 int defaultLayout = idp.defaultLayoutId;
537
538 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
539 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
540 defaultLayout = idp.demoModeLayoutId;
541 }
542
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700543 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700544 mOpenHelper, getContext().getResources(), defaultLayout);
545 }
546
Sunny Goyald3849d12015-10-29 10:28:32 -0700547 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800548 * The class is subclassed in tests to create an in-memory db.
549 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700550 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700551 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700553 private long mMaxItemId = -1;
554 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800555
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700556 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
557 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700558 // Table creation sometimes fails silently, which leads to a crash loop.
559 // This way, we will try to create a table every time after crash, so the device
560 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700561 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700562 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
563 // This operation is a no-op if the table already exists.
564 addFavoritesTable(getWritableDatabase(), true);
565 addWorkspacesTable(getWritableDatabase(), true);
566 }
567
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700568 initIds();
569 }
570
571 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700572 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700573 */
574 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700575 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700576 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700578 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700579 }
580
581 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700582 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
583 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700584 if (mMaxItemId == -1) {
585 mMaxItemId = initializeMaxItemId(getWritableDatabase());
586 }
587 if (mMaxScreenId == -1) {
588 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700589 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800590 }
591
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700592 private boolean tableExists(String tableName) {
593 Cursor c = getReadableDatabase().query(
594 true, "sqlite_master", new String[] {"tbl_name"},
595 "tbl_name = ?", new String[] {tableName},
596 null, null, null, null, null);
597 try {
598 return c.getCount() > 0;
599 } finally {
600 c.close();
601 }
602 }
603
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800604 @Override
605 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800606 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700607
Adam Cohendcd297f2013-06-18 13:13:40 -0700608 mMaxItemId = 1;
609 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700610
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700611 addFavoritesTable(db, false);
612 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800614 // Fresh and clean launcher DB.
615 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800616 onEmptyDbCreated();
617 }
618
619 /**
620 * Overriden in tests.
621 */
622 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700623 // Database was just created, so wipe any previous widgets
624 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700625 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700626 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530627 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700628 }
629
Sunny Goyalf076eae2016-01-11 12:25:10 -0800630 // Set the flag for empty DB
631 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700632
633 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800634 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800635 mContext);
636 }
637
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700638 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800639 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800640 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641 }
642
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700644 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700645 }
646
647 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
648 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700649 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800650 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400651 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
652 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 ");");
654 }
655
Adam Cohen119285e2014-04-02 16:59:08 -0700656 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700657 // Delete items directly on the workspace who's screen id doesn't exist
658 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
659 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700660 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700661 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700662 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700663 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700664 " AND " +
665 LauncherSettings.Favorites.CONTAINER + " = " +
666 LauncherSettings.Favorites.CONTAINER_DESKTOP;
667 db.execSQL(removeOrphanedDesktopItems);
668
669 // Delete items contained in folders which no longer exist (after above statement)
670 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
671 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700672 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 " WHERE " +
674 LauncherSettings.Favorites.CONTAINER + " <> " +
675 LauncherSettings.Favorites.CONTAINER_DESKTOP +
676 " AND "
677 + LauncherSettings.Favorites.CONTAINER + " <> " +
678 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
679 " AND "
680 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700681 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700682 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
683 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
684 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700685 }
686
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700688 public void onOpen(SQLiteDatabase db) {
689 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700690
691 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
692 if (!schemaFile.exists()) {
693 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700694 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700695 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
696 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700697 }
698
699 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700700 * One-time data updated before support of onDowngrade was added. This update is backwards
701 * compatible and can safely be run multiple times.
702 * Note: No new logic should be added here after release, as the new logic might not get
703 * executed on an existing device.
704 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700705 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700706 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
707 // Remove "profile extra"
708 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
709 for (UserHandle user : um.getUserProfiles()) {
710 long serial = um.getSerialNumberForUser(user);
711 String sql = "update favorites set intent = replace(intent, "
712 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
713 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700714 }
715 }
716
717 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700719 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800720 switch (oldVersion) {
721 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800722 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800723 case 12: {
724 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
725 // to persist workspace screens and their relative order.
726 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700727 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800728 }
729 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700730 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800731 // Insert new column for holding widget provider name
732 db.execSQL("ALTER TABLE favorites " +
733 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700734 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 } catch (SQLException ex) {
736 Log.e(TAG, ex.getMessage(), ex);
737 // Old version remains, which means we wipe old data
738 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800739 }
740 }
741 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700742 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 // Insert new column for holding update timestamp
744 db.execSQL("ALTER TABLE favorites " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
746 db.execSQL("ALTER TABLE workspaceScreens " +
747 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700748 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800749 } catch (SQLException ex) {
750 Log.e(TAG, ex.getMessage(), ex);
751 // Old version remains, which means we wipe old data
752 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 }
754 }
755 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700756 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 // Old version remains, which means we wipe old data
758 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 }
760 }
761 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700762 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800763 }
764 case 17: {
765 // No-op
766 }
767 case 18: {
768 // Due to a data loss bug, some users may have items associated with screen ids
769 // which no longer exist. Since this can cause other problems, and since the user
770 // will never see these items anyway, we use database upgrade as an opportunity to
771 // clean things up.
772 removeOrphanedItems(db);
773 }
774 case 19: {
775 // Add userId column
776 if (!addProfileColumn(db)) {
777 // Old version remains, which means we wipe old data
778 break;
779 }
780 }
781 case 20:
782 if (!updateFolderItemsRank(db, true)) {
783 break;
784 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800785 case 21:
786 // Recreate workspace table with screen id a primary key
787 if (!recreateWorkspaceTable(db)) {
788 break;
789 }
790 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700791 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
792 // Old version remains, which means we wipe old data
793 break;
794 }
795 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700796 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700797 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700798 case 24:
799 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700800 case 25:
801 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700802 case 26:
803 // QSB was moved to the grid. Clear the first row on screen 0.
804 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800805 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700806 break;
807 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700808 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800809 // DB Upgraded successfully
810 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400811 }
812
Sunny Goyala2cc6242015-01-14 14:23:02 -0800813 // DB was not upgraded
814 Log.w(TAG, "Destroying all old data.");
815 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800816 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800817
Adam Cohen9b1d0622014-05-21 19:01:57 -0700818 @Override
819 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700820 try {
821 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
822 .onDowngrade(db, oldVersion, newVersion);
823 } catch (Exception e) {
824 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
825 ". Wiping databse.", e);
826 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700827 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700828 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700829
Sunny Goyal42de82f2014-09-26 22:09:29 -0700830 /**
831 * Clears all the data for a fresh start.
832 */
833 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700834 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800835 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
836 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
837 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700838 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800839 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700840 }
841
Sunny Goyald2f38192015-02-25 10:46:34 -0800842 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700843 * Removes widgets which are registered to the Launcher's host, but are not present
844 * in our model.
845 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700846 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700847 public void removeGhostWidgets(SQLiteDatabase db) {
848 // Get all existing widget ids.
849 final AppWidgetHost host = newLauncherWidgetHost();
850 final int[] allWidgets;
851 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700852 // Although the method was defined in O, it has existed since the beginning of time,
853 // so it might work on older platforms as well.
854 allWidgets = host.getAppWidgetIds();
855 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700856 Log.e(TAG, "getAppWidgetIds not supported", e);
857 return;
858 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700859 final HashSet<Integer> validWidgets = new HashSet<>();
860 try (Cursor c = db.query(Favorites.TABLE_NAME,
861 new String[] {Favorites.APPWIDGET_ID },
862 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700863 while (c.moveToNext()) {
864 validWidgets.add(c.getInt(0));
865 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700866 } catch (SQLException ex) {
867 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700868 return;
869 }
870 for (int widgetId : allWidgets) {
871 if (!validWidgets.contains(widgetId)) {
872 try {
873 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
874 host.deleteAppWidgetId(widgetId);
875 } catch (RuntimeException e) {
876 // Ignore
877 }
878 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700879 }
880 }
881
882 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700883 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
884 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
885 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700886 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700887 try (SQLiteTransaction t = new SQLiteTransaction(db);
888 // Only consider the primary user as other users can't have a shortcut.
889 Cursor c = db.query(Favorites.TABLE_NAME,
890 new String[] { Favorites._ID, Favorites.INTENT},
891 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
892 " AND profileId=" + getDefaultUserSerial(),
893 null, null, null, null);
894 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
895 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
896 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700897 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
898 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
899
900 while (c.moveToNext()) {
901 String intentDescription = c.getString(intentIndex);
902 Intent intent;
903 try {
904 intent = Intent.parseUri(intentDescription, 0);
905 } catch (URISyntaxException e) {
906 Log.e(TAG, "Unable to parse intent", e);
907 continue;
908 }
909
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700910 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700911 continue;
912 }
913
914 long id = c.getLong(idIndex);
915 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700916 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700917 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700918 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700919 } catch (SQLException ex) {
920 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700921 }
922 }
923
924 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800925 * Recreates workspace table and migrates data to the new table.
926 */
927 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700928 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
929 final ArrayList<Long> sortedIDs;
930
931 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800932 new String[] {LauncherSettings.WorkspaceScreens._ID},
933 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700934 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
935 // Use LinkedHashSet so that ordering is preserved
936 sortedIDs = new ArrayList<>(
937 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800938 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700939 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700940 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800941
942 // Add all screen ids back
943 int total = sortedIDs.size();
944 for (int i = 0; i < total; i++) {
945 ContentValues values = new ContentValues();
946 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
947 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
948 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700949 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800950 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700951 t.commit();
952 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800953 } catch (SQLException ex) {
954 // Old version remains, which means we wipe old data
955 Log.e(TAG, ex.getMessage(), ex);
956 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800957 }
958 return true;
959 }
960
Adam Cohen091440a2015-03-18 14:16:05 -0700961 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700962 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800963 if (addRankColumn) {
964 // Insert new column for holding rank
965 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
966 }
967
968 // Get a map for folder ID to folder width
969 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
970 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
971 + " GROUP BY container;",
972 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
973
974 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800975 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
976 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800977 new Object[] {c.getLong(1) + 1, c.getLong(0)});
978 }
979
980 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700981 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800982 } catch (SQLException ex) {
983 // Old version remains, which means we wipe old data
984 Log.e(TAG, ex.getMessage(), ex);
985 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800986 }
987 return true;
988 }
989
Kenny Guyed131872014-04-30 03:02:21 +0100990 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700991 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700992 }
993
994 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700995 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700996 db.execSQL("ALTER TABLE favorites ADD COLUMN "
997 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700998 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100999 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001000 Log.e(TAG, ex.getMessage(), ex);
1001 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001002 }
1003 return true;
1004 }
1005
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 // Generates a new ID to use for an object in your database. This method should be only
1007 // called from the main UI thread. As an exception, we do call it when we call the
1008 // constructor from the worker thread; however, this doesn't extend until after the
1009 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1010 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001011 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 public long generateNewItemId() {
1013 if (mMaxItemId < 0) {
1014 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 mMaxItemId += 1;
1017 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001018 }
1019
Sunny Goyal55fddc82017-04-06 15:02:52 -07001020 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001021 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001022 }
1023
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001024 @Override
1025 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001026 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001027 }
1028
Chris Wren5dee7af2013-12-20 17:22:11 -05001029 public void checkId(String table, ContentValues values) {
1030 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001031 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001032 mMaxScreenId = Math.max(id, mMaxScreenId);
1033 } else {
1034 mMaxItemId = Math.max(id, mMaxItemId);
1035 }
1036 }
1037
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001039 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001040 }
1041
1042 // Generates a new ID to use for an workspace screen in your database. This method
1043 // should be only called from the main UI thread. As an exception, we do call it when we
1044 // call the constructor from the worker thread; however, this doesn't extend until after the
1045 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1046 // after that point
1047 public long generateNewScreenId() {
1048 if (mMaxScreenId < 0) {
1049 throw new RuntimeException("Error: max screen id was not initialized");
1050 }
1051 mMaxScreenId += 1;
1052 return mMaxScreenId;
1053 }
1054
Adam Cohendcd297f2013-06-18 13:13:40 -07001055 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001056 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001057 }
1058
Adam Cohen091440a2015-03-18 14:16:05 -07001059 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001060 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001061 // TODO: Use multiple loaders with fall-back and transaction.
1062 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001063
1064 // Add the screens specified by the items above
1065 Collections.sort(screenIds);
1066 int rank = 0;
1067 ContentValues values = new ContentValues();
1068 for (Long id : screenIds) {
1069 values.clear();
1070 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1071 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001072 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001073 throw new RuntimeException("Failed initialize screen table"
1074 + "from default layout");
1075 }
1076 rank++;
1077 }
1078
1079 // Ensure that the max ids are initialized
1080 mMaxItemId = initializeMaxItemId(db);
1081 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001082
Adam Cohen71483f42014-05-15 14:04:01 -07001083 return count;
1084 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001085 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001086
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001087 /**
1088 * @return the max _id in the provided table.
1089 */
Adam Cohen091440a2015-03-18 14:16:05 -07001090 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001091 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1092 // get the result
1093 long id = -1;
1094 if (c != null && c.moveToNext()) {
1095 id = c.getLong(0);
1096 }
1097 if (c != null) {
1098 c.close();
1099 }
1100
1101 if (id == -1) {
1102 throw new RuntimeException("Error: could not query max id in " + table);
1103 }
1104
1105 return id;
1106 }
1107
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001108 static class SqlArguments {
1109 public final String table;
1110 public final String where;
1111 public final String[] args;
1112
1113 SqlArguments(Uri url, String where, String[] args) {
1114 if (url.getPathSegments().size() == 1) {
1115 this.table = url.getPathSegments().get(0);
1116 this.where = where;
1117 this.args = args;
1118 } else if (url.getPathSegments().size() != 2) {
1119 throw new IllegalArgumentException("Invalid URI: " + url);
1120 } else if (!TextUtils.isEmpty(where)) {
1121 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1122 } else {
1123 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001124 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001125 this.args = null;
1126 }
1127 }
1128
1129 SqlArguments(Uri url) {
1130 if (url.getPathSegments().size() == 1) {
1131 table = url.getPathSegments().get(0);
1132 where = null;
1133 args = null;
1134 } else {
1135 throw new IllegalArgumentException("Invalid URI: " + url);
1136 }
1137 }
1138 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001139
1140 private static class ChangeListenerWrapper implements Handler.Callback {
1141
1142 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001143 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001144
1145 private LauncherProviderChangeListener mListener;
1146
1147 @Override
1148 public boolean handleMessage(Message msg) {
1149 if (mListener != null) {
1150 switch (msg.what) {
1151 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001152 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001153 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001154 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001155 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001156 break;
1157 }
1158 }
1159 return true;
1160 }
1161 }
Adam Cohen72960972014-01-15 18:13:55 -08001162}