blob: 98568e43638f01a7b7ae99703aef60d89d2438bb [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 Goyalca187462017-03-31 20:09:34 -070057import com.android.launcher3.graphics.IconShapeOverride;
Sunny Goyalfdbef272017-02-01 12:52:54 -080058import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070059import com.android.launcher3.model.DbDowngradeHelper;
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
119 // is the first component to get created. Initializing FileLog here ensures that it's
120 // always available in the main process.
121 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700122 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700123 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800124 return true;
125 }
126
Sunny Goyald3849d12015-10-29 10:28:32 -0700127 /**
128 * Sets a provider listener.
129 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700130 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700131 Preconditions.assertUIThread();
132 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700133 }
134
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800135 @Override
136 public String getType(Uri uri) {
137 SqlArguments args = new SqlArguments(uri, null, null);
138 if (TextUtils.isEmpty(args.where)) {
139 return "vnd.android.cursor.dir/" + args.table;
140 } else {
141 return "vnd.android.cursor.item/" + args.table;
142 }
143 }
144
Sunny Goyalf076eae2016-01-11 12:25:10 -0800145 /**
146 * Overridden in tests
147 */
148 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700149 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700150 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700151
152 if (RestoreDbTask.isPending(getContext())) {
153 if (!RestoreDbTask.performRestore(mOpenHelper)) {
154 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
155 }
156 // Set is pending to false irrespective of the result, so that it doesn't get
157 // executed again.
158 RestoreDbTask.setPending(getContext(), false);
159 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700160 }
161 }
162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public Cursor query(Uri uri, String[] projection, String selection,
165 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700166 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
168 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
169 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
170 qb.setTables(args.table);
171
Romain Guy73b979d2009-06-09 12:57:21 -0700172 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
174 result.setNotificationUri(getContext().getContentResolver(), uri);
175
176 return result;
177 }
178
Adam Cohen091440a2015-03-18 14:16:05 -0700179 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700180 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500181 if (values == null) {
182 throw new RuntimeException("Error: attempting to insert null values");
183 }
Adam Cohen71483f42014-05-15 14:04:01 -0700184 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700185 throw new RuntimeException("Error: attempting to add item without specifying an id");
186 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500187 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700188 return db.insert(table, nullColumnHack, values);
189 }
190
Sunny Goyald1064182015-08-13 12:08:30 -0700191 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700192 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700193 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
194 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800195 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700196 }
197 }
198 }
199
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 @Override
201 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700202 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 SqlArguments args = new SqlArguments(uri);
204
Sunny Goyald1064182015-08-13 12:08:30 -0700205 // In very limited cases, we support system|signature permission apps to modify the db.
206 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700207 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700208 return null;
209 }
210 }
211
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400213 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700214 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800215 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
217 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700218 notifyListeners();
219
Sunny Goyalc74e4192015-09-08 14:01:03 -0700220 if (Utilities.ATLEAST_MARSHMALLOW) {
221 reloadLauncherIfExternal();
222 } else {
223 // Deprecated behavior to support legacy devices which rely on provider callbacks.
224 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
225 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800226 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700227 }
228
229 String notify = uri.getQueryParameter("notify");
230 if (notify == null || "true".equals(notify)) {
231 getContext().getContentResolver().notifyChange(uri, null);
232 }
233 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 return uri;
235 }
236
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700237 private boolean initializeExternalAdd(ContentValues values) {
238 // 1. Ensure that externally added items have a valid item id
239 long id = mOpenHelper.generateNewItemId();
240 values.put(LauncherSettings.Favorites._ID, id);
241
242 // 2. In the case of an app widget, and if no app widget id is specified, we
243 // attempt allocate and bind the widget.
244 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
245 if (itemType != null &&
246 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
247 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
248
249 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
250 ComponentName cn = ComponentName.unflattenFromString(
251 values.getAsString(Favorites.APPWIDGET_PROVIDER));
252
253 if (cn != null) {
254 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700255 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
256 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700257 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
258 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700259 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700260 return false;
261 }
262 } catch (RuntimeException e) {
263 Log.e(TAG, "Failed to initialize external widget", e);
264 return false;
265 }
266 } else {
267 return false;
268 }
269 }
270
271 // Add screen id if not present
272 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
273 SQLiteStatement stmp = null;
274 try {
275 stmp = mOpenHelper.getWritableDatabase().compileStatement(
276 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
277 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
278 stmp.bindLong(1, screenId);
279
280 ContentValues valuesInserted = new ContentValues();
281 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
282 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
283 return true;
284 } catch (Exception e) {
285 return false;
286 } finally {
287 Utilities.closeSilently(stmp);
288 }
289 }
290
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 @Override
292 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700293 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 SqlArguments args = new SqlArguments(uri);
295
296 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700297 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800298 int numValues = values.length;
299 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400300 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700301 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
302 return 0;
303 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700305 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 }
307
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700308 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700309 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 return values.length;
311 }
312
313 @Override
Yura085c8532014-02-11 15:15:29 +0000314 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
315 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700316 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700317 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000318 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700319 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700320 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000321 return result;
Yura085c8532014-02-11 15:15:29 +0000322 }
323 }
324
325 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800326 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700327 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
329
330 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331
Louis Begina9c21c62016-08-15 15:18:41 -0700332 if (Binder.getCallingPid() != Process.myPid()
333 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700334 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700335 }
336 int count = db.delete(args.table, args.where, args.args);
337 if (count > 0) {
338 notifyListeners();
339 reloadLauncherIfExternal();
340 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341 return count;
342 }
343
344 @Override
345 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700346 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
348
Chris Wren1ada10d2013-09-13 18:01:38 -0400349 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
351 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700352 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800353
Sunny Goyald1064182015-08-13 12:08:30 -0700354 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 return count;
356 }
357
Sunny Goyal7779d622015-06-11 16:18:39 -0700358 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700359 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 if (Binder.getCallingUid() != Process.myUid()) {
361 return null;
362 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700363 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700364
365 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700366 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
367 clearFlagEmptyDbCreated();
368 return null;
369 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700370 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
371 Bundle result = new Bundle();
372 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
373 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
374 return result;
375 }
Sunny Goyald2497482015-09-22 18:24:19 -0700376 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
377 Bundle result = new Bundle();
378 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
379 return result;
380 }
381 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
382 Bundle result = new Bundle();
383 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
384 return result;
385 }
386 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
387 Bundle result = new Bundle();
388 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
389 return result;
390 }
391 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800392 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700393 return null;
394 }
395 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
396 loadDefaultFavoritesIfNecessary();
397 return null;
398 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700399 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
400 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
401 return null;
402 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700403 }
404 return null;
405 }
406
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700407 /**
408 * Deletes any empty folder from the DB.
409 * @return Ids of deleted folders.
410 */
Sunny Goyald2497482015-09-22 18:24:19 -0700411 private ArrayList<Long> deleteEmptyFolders() {
412 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700413 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700414 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700415 // Select folders whose id do not match any container value.
416 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
417 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
418 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
419 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700420 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700421 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700422 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700423 selection, null, null, null, null)) {
424 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700425 }
Sunny Goyald2497482015-09-22 18:24:19 -0700426 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700427 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 LauncherSettings.Favorites._ID, folderIds), null);
429 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700430 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700431 } catch (SQLException ex) {
432 Log.e(TAG, ex.getMessage(), ex);
433 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700434 }
435 return folderIds;
436 }
437
Sunny Goyalf076eae2016-01-11 12:25:10 -0800438 /**
439 * Overridden in tests
440 */
441 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700442 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400443 }
444
Adam Cohen091440a2015-03-18 14:16:05 -0700445 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400446 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800447 }
448
Sunny Goyald2497482015-09-22 18:24:19 -0700449 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700450 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700451 }
452
Sunny Goyal42de82f2014-09-26 22:09:29 -0700453 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700454 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700455 * 1) From the app restrictions
456 * 2) From a package provided by play store
457 * 3) From a partner configuration APK, already in the system image
458 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700459 */
Sunny Goyald2497482015-09-22 18:24:19 -0700460 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700461 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700462
Winson Chungc763c4e2013-07-19 13:49:06 -0700463 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500464 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200465
Sunny Goyal55fddc82017-04-06 15:02:52 -0700466 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700467 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700468 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700469 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700470 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700471 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700472 final Partner partner = Partner.get(getContext().getPackageManager());
473 if (partner != null && partner.hasDefaultLayout()) {
474 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700475 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700476 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700477 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700478 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700479 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700481 }
482 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700483
Sunny Goyal9d219682014-10-23 14:21:02 -0700484 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700485 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700486 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700487 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800488
489 // There might be some partially restored DB items, due to buggy restore logic in
490 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800491 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700492 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700493 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
494 && usingExternallyProvidedLayout) {
495 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800496 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700497 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700498 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700499 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700500 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700501 }
502 }
503
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700504 /**
505 * Creates workspace loader from an XML resource listed in the app restrictions.
506 *
507 * @return the loader if the restrictions are set and the resource exists; null otherwise.
508 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700509 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700510 Context ctx = getContext();
511 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
512 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700513 if (bundle == null) {
514 return null;
515 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700516
Sunny Goyal35ca8732015-04-06 10:45:31 -0700517 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700518 if (packageName != null) {
519 try {
520 Resources targetResources = ctx.getPackageManager()
521 .getResourcesForApplication(packageName);
522 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700523 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700524 } catch (NameNotFoundException e) {
525 Log.e(TAG, "Target package for restricted profile not found", e);
526 return null;
527 }
528 }
529 return null;
530 }
531
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700532 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700533 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
534 int defaultLayout = idp.defaultLayoutId;
535
536 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
537 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
538 defaultLayout = idp.demoModeLayoutId;
539 }
540
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700541 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700542 mOpenHelper, getContext().getResources(), defaultLayout);
543 }
544
Sunny Goyald3849d12015-10-29 10:28:32 -0700545 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800546 * The class is subclassed in tests to create an in-memory db.
547 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700548 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700549 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700551 private long mMaxItemId = -1;
552 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800553
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700554 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
555 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700556 // Table creation sometimes fails silently, which leads to a crash loop.
557 // This way, we will try to create a table every time after crash, so the device
558 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700559 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700560 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
561 // This operation is a no-op if the table already exists.
562 addFavoritesTable(getWritableDatabase(), true);
563 addWorkspacesTable(getWritableDatabase(), true);
564 }
565
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700566 initIds();
567 }
568
569 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700570 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700571 */
572 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700573 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700574 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700575 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700576 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 }
578
579 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700580 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
581 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700582 if (mMaxItemId == -1) {
583 mMaxItemId = initializeMaxItemId(getWritableDatabase());
584 }
585 if (mMaxScreenId == -1) {
586 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700587 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800588 }
589
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700590 private boolean tableExists(String tableName) {
591 Cursor c = getReadableDatabase().query(
592 true, "sqlite_master", new String[] {"tbl_name"},
593 "tbl_name = ?", new String[] {tableName},
594 null, null, null, null, null);
595 try {
596 return c.getCount() > 0;
597 } finally {
598 c.close();
599 }
600 }
601
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 @Override
603 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800604 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700605
Adam Cohendcd297f2013-06-18 13:13:40 -0700606 mMaxItemId = 1;
607 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700608
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700609 addFavoritesTable(db, false);
610 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800612 // Fresh and clean launcher DB.
613 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800614 onEmptyDbCreated();
615 }
616
617 /**
618 * Overriden in tests.
619 */
620 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700621 // Database was just created, so wipe any previous widgets
622 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700623 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700624 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530625 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700626 }
627
Sunny Goyalf076eae2016-01-11 12:25:10 -0800628 // Set the flag for empty DB
629 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700630
631 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800632 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 mContext);
634 }
635
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700636 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800637 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800638 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 }
640
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700641 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700642 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 }
644
645 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
646 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700647 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800648 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400649 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
650 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 ");");
652 }
653
Adam Cohen119285e2014-04-02 16:59:08 -0700654 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700655 // Delete items directly on the workspace who's screen id doesn't exist
656 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
657 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700658 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700659 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700660 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700661 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700662 " AND " +
663 LauncherSettings.Favorites.CONTAINER + " = " +
664 LauncherSettings.Favorites.CONTAINER_DESKTOP;
665 db.execSQL(removeOrphanedDesktopItems);
666
667 // Delete items contained in folders which no longer exist (after above statement)
668 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
669 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700670 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700671 " WHERE " +
672 LauncherSettings.Favorites.CONTAINER + " <> " +
673 LauncherSettings.Favorites.CONTAINER_DESKTOP +
674 " AND "
675 + LauncherSettings.Favorites.CONTAINER + " <> " +
676 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
677 " AND "
678 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700679 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700680 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
681 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
682 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700683 }
684
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800685 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700686 public void onOpen(SQLiteDatabase db) {
687 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700688
689 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
690 if (!schemaFile.exists()) {
691 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700692 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700693 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
694 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700695 }
696
697 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700698 * One-time data updated before support of onDowngrade was added. This update is backwards
699 * compatible and can safely be run multiple times.
700 * Note: No new logic should be added here after release, as the new logic might not get
701 * executed on an existing device.
702 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700703 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700704 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
705 // Remove "profile extra"
706 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
707 for (UserHandle user : um.getUserProfiles()) {
708 long serial = um.getSerialNumberForUser(user);
709 String sql = "update favorites set intent = replace(intent, "
710 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
711 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700712 }
713 }
714
715 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700717 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800718 switch (oldVersion) {
719 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800720 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800721 case 12: {
722 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
723 // to persist workspace screens and their relative order.
724 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700725 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800726 }
727 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700728 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800729 // Insert new column for holding widget provider name
730 db.execSQL("ALTER TABLE favorites " +
731 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700732 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 } catch (SQLException ex) {
734 Log.e(TAG, ex.getMessage(), ex);
735 // Old version remains, which means we wipe old data
736 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 }
738 }
739 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700740 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800741 // Insert new column for holding update timestamp
742 db.execSQL("ALTER TABLE favorites " +
743 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
744 db.execSQL("ALTER TABLE workspaceScreens " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700746 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800747 } catch (SQLException ex) {
748 Log.e(TAG, ex.getMessage(), ex);
749 // Old version remains, which means we wipe old data
750 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 }
752 }
753 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700754 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 // Old version remains, which means we wipe old data
756 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 }
758 }
759 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700760 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 }
762 case 17: {
763 // No-op
764 }
765 case 18: {
766 // Due to a data loss bug, some users may have items associated with screen ids
767 // which no longer exist. Since this can cause other problems, and since the user
768 // will never see these items anyway, we use database upgrade as an opportunity to
769 // clean things up.
770 removeOrphanedItems(db);
771 }
772 case 19: {
773 // Add userId column
774 if (!addProfileColumn(db)) {
775 // Old version remains, which means we wipe old data
776 break;
777 }
778 }
779 case 20:
780 if (!updateFolderItemsRank(db, true)) {
781 break;
782 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800783 case 21:
784 // Recreate workspace table with screen id a primary key
785 if (!recreateWorkspaceTable(db)) {
786 break;
787 }
788 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700789 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
790 // Old version remains, which means we wipe old data
791 break;
792 }
793 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700794 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700795 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700796 case 24:
797 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700798 case 25:
799 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700800 case 26:
801 // QSB was moved to the grid. Clear the first row on screen 0.
802 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800803 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700804 break;
805 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700806 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800807 // DB Upgraded successfully
808 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400809 }
810
Sunny Goyala2cc6242015-01-14 14:23:02 -0800811 // DB was not upgraded
812 Log.w(TAG, "Destroying all old data.");
813 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800814 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800815
Adam Cohen9b1d0622014-05-21 19:01:57 -0700816 @Override
817 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700818 try {
819 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
820 .onDowngrade(db, oldVersion, newVersion);
821 } catch (Exception e) {
822 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
823 ". Wiping databse.", e);
824 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700825 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700826 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700827
Sunny Goyal42de82f2014-09-26 22:09:29 -0700828 /**
829 * Clears all the data for a fresh start.
830 */
831 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700832 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800833 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
834 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
835 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700836 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800837 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700838 }
839
Sunny Goyald2f38192015-02-25 10:46:34 -0800840 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700841 * Removes widgets which are registered to the Launcher's host, but are not present
842 * in our model.
843 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700844 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700845 public void removeGhostWidgets(SQLiteDatabase db) {
846 // Get all existing widget ids.
847 final AppWidgetHost host = newLauncherWidgetHost();
848 final int[] allWidgets;
849 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700850 // Although the method was defined in O, it has existed since the beginning of time,
851 // so it might work on older platforms as well.
852 allWidgets = host.getAppWidgetIds();
853 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700854 Log.e(TAG, "getAppWidgetIds not supported", e);
855 return;
856 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700857 final HashSet<Integer> validWidgets = new HashSet<>();
858 try (Cursor c = db.query(Favorites.TABLE_NAME,
859 new String[] {Favorites.APPWIDGET_ID },
860 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700861 while (c.moveToNext()) {
862 validWidgets.add(c.getInt(0));
863 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700864 } catch (SQLException ex) {
865 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700866 return;
867 }
868 for (int widgetId : allWidgets) {
869 if (!validWidgets.contains(widgetId)) {
870 try {
871 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
872 host.deleteAppWidgetId(widgetId);
873 } catch (RuntimeException e) {
874 // Ignore
875 }
876 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700877 }
878 }
879
880 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700881 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
882 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
883 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700884 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700885 try (SQLiteTransaction t = new SQLiteTransaction(db);
886 // Only consider the primary user as other users can't have a shortcut.
887 Cursor c = db.query(Favorites.TABLE_NAME,
888 new String[] { Favorites._ID, Favorites.INTENT},
889 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
890 " AND profileId=" + getDefaultUserSerial(),
891 null, null, null, null);
892 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
893 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
894 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700895 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
896 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
897
898 while (c.moveToNext()) {
899 String intentDescription = c.getString(intentIndex);
900 Intent intent;
901 try {
902 intent = Intent.parseUri(intentDescription, 0);
903 } catch (URISyntaxException e) {
904 Log.e(TAG, "Unable to parse intent", e);
905 continue;
906 }
907
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700908 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700909 continue;
910 }
911
912 long id = c.getLong(idIndex);
913 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700914 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700915 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700916 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700917 } catch (SQLException ex) {
918 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700919 }
920 }
921
922 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800923 * Recreates workspace table and migrates data to the new table.
924 */
925 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700926 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
927 final ArrayList<Long> sortedIDs;
928
929 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800930 new String[] {LauncherSettings.WorkspaceScreens._ID},
931 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700932 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
933 // Use LinkedHashSet so that ordering is preserved
934 sortedIDs = new ArrayList<>(
935 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800936 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700937 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700938 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800939
940 // Add all screen ids back
941 int total = sortedIDs.size();
942 for (int i = 0; i < total; i++) {
943 ContentValues values = new ContentValues();
944 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
945 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
946 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700947 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800948 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700949 t.commit();
950 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800951 } catch (SQLException ex) {
952 // Old version remains, which means we wipe old data
953 Log.e(TAG, ex.getMessage(), ex);
954 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800955 }
956 return true;
957 }
958
Adam Cohen091440a2015-03-18 14:16:05 -0700959 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700960 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800961 if (addRankColumn) {
962 // Insert new column for holding rank
963 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
964 }
965
966 // Get a map for folder ID to folder width
967 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
968 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
969 + " GROUP BY container;",
970 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
971
972 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800973 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
974 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800975 new Object[] {c.getLong(1) + 1, c.getLong(0)});
976 }
977
978 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700979 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800980 } catch (SQLException ex) {
981 // Old version remains, which means we wipe old data
982 Log.e(TAG, ex.getMessage(), ex);
983 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800984 }
985 return true;
986 }
987
Kenny Guyed131872014-04-30 03:02:21 +0100988 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700989 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700990 }
991
992 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700993 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700994 db.execSQL("ALTER TABLE favorites ADD COLUMN "
995 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700996 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100997 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100998 Log.e(TAG, ex.getMessage(), ex);
999 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001000 }
1001 return true;
1002 }
1003
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001004 // Generates a new ID to use for an object in your database. This method should be only
1005 // called from the main UI thread. As an exception, we do call it when we call the
1006 // constructor from the worker thread; however, this doesn't extend until after the
1007 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1008 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001009 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001010 public long generateNewItemId() {
1011 if (mMaxItemId < 0) {
1012 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001014 mMaxItemId += 1;
1015 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001016 }
1017
Sunny Goyal55fddc82017-04-06 15:02:52 -07001018 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001019 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001020 }
1021
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001022 @Override
1023 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001024 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001025 }
1026
Chris Wren5dee7af2013-12-20 17:22:11 -05001027 public void checkId(String table, ContentValues values) {
1028 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001029 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001030 mMaxScreenId = Math.max(id, mMaxScreenId);
1031 } else {
1032 mMaxItemId = Math.max(id, mMaxItemId);
1033 }
1034 }
1035
Adam Cohendcd297f2013-06-18 13:13:40 -07001036 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001037 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 }
1039
1040 // Generates a new ID to use for an workspace screen in your database. This method
1041 // should be only called from the main UI thread. As an exception, we do call it when we
1042 // call the constructor from the worker thread; however, this doesn't extend until after the
1043 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1044 // after that point
1045 public long generateNewScreenId() {
1046 if (mMaxScreenId < 0) {
1047 throw new RuntimeException("Error: max screen id was not initialized");
1048 }
1049 mMaxScreenId += 1;
1050 return mMaxScreenId;
1051 }
1052
Adam Cohendcd297f2013-06-18 13:13:40 -07001053 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001054 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001055 }
1056
Adam Cohen091440a2015-03-18 14:16:05 -07001057 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001058 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001059 // TODO: Use multiple loaders with fall-back and transaction.
1060 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001061
1062 // Add the screens specified by the items above
1063 Collections.sort(screenIds);
1064 int rank = 0;
1065 ContentValues values = new ContentValues();
1066 for (Long id : screenIds) {
1067 values.clear();
1068 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1069 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001070 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001071 throw new RuntimeException("Failed initialize screen table"
1072 + "from default layout");
1073 }
1074 rank++;
1075 }
1076
1077 // Ensure that the max ids are initialized
1078 mMaxItemId = initializeMaxItemId(db);
1079 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001080
Adam Cohen71483f42014-05-15 14:04:01 -07001081 return count;
1082 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001083 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001084
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001085 /**
1086 * @return the max _id in the provided table.
1087 */
Adam Cohen091440a2015-03-18 14:16:05 -07001088 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001089 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1090 // get the result
1091 long id = -1;
1092 if (c != null && c.moveToNext()) {
1093 id = c.getLong(0);
1094 }
1095 if (c != null) {
1096 c.close();
1097 }
1098
1099 if (id == -1) {
1100 throw new RuntimeException("Error: could not query max id in " + table);
1101 }
1102
1103 return id;
1104 }
1105
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001106 static class SqlArguments {
1107 public final String table;
1108 public final String where;
1109 public final String[] args;
1110
1111 SqlArguments(Uri url, String where, String[] args) {
1112 if (url.getPathSegments().size() == 1) {
1113 this.table = url.getPathSegments().get(0);
1114 this.where = where;
1115 this.args = args;
1116 } else if (url.getPathSegments().size() != 2) {
1117 throw new IllegalArgumentException("Invalid URI: " + url);
1118 } else if (!TextUtils.isEmpty(where)) {
1119 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1120 } else {
1121 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001122 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001123 this.args = null;
1124 }
1125 }
1126
1127 SqlArguments(Uri url) {
1128 if (url.getPathSegments().size() == 1) {
1129 table = url.getPathSegments().get(0);
1130 where = null;
1131 args = null;
1132 } else {
1133 throw new IllegalArgumentException("Invalid URI: " + url);
1134 }
1135 }
1136 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001137
1138 private static class ChangeListenerWrapper implements Handler.Callback {
1139
1140 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001141 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001142
1143 private LauncherProviderChangeListener mListener;
1144
1145 @Override
1146 public boolean handleMessage(Message msg) {
1147 if (mListener != null) {
1148 switch (msg.what) {
1149 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001150 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001151 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001152 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001153 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001154 break;
1155 }
1156 }
1157 return true;
1158 }
1159 }
Adam Cohen72960972014-01-15 18:13:55 -08001160}