blob: bd53b4d72359e6771b6d3cdcf82745ec2171b205 [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
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070025import android.content.ContentUris;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000029import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070030import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070031import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070038import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070040import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070041import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070042import android.os.Handler;
43import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070044import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070045import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080046import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070050
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
52import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070053import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070055import com.android.launcher3.config.FeatureFlags;
Tony Wickham827cef22016-03-17 15:39:39 -070056import com.android.launcher3.dynamicui.ExtractionUtils;
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 Goyala9e2f5a2016-06-10 12:22:04 -070059import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070060import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070063import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Hyunyoung Song6aa37292017-02-06 10:46:24 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Sunny Goyal55fddc82017-04-06 15:02:52 -070069import java.lang.reflect.Method;
Mike Cleronb87bd162009-10-30 16:36:56 -070070import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070071import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070072import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070073import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070074import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070077 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080078 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070080 /**
81 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
82 */
83 private static final int SCHEMA_VERSION = 27;
84 /**
85 * Represents the actual data. It could include additional validations and normalizations added
86 * overtime. These must be backwards compatible, else we risk breaking old devices during
87 * restore or binary version downgrade.
88 */
Sunny Goyal55fddc82017-04-06 15:02:52 -070089 private static final int DATA_VERSION = 3;
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070090
91 private static final String PREF_KEY_DATA_VERISON = "provider_data_version";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Sunny Goyal3d706ad2017-03-06 16:56:39 -080093 public static final String AUTHORITY = (BuildConfig.APPLICATION_ID + ".settings").intern();
Winson Chung3d503fb2011-07-13 17:25:49 -070094
Sunny Goyale87e6ab2014-11-21 22:42:53 -080095 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070097 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
98
Sunny Goyalb5b55c82016-05-10 12:28:59 -070099 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
100 private Handler mListenerHandler;
101
Sunny Goyalf076eae2016-01-11 12:25:10 -0800102 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800104 /**
105 * $ adb shell dumpsys activity provider com.android.launcher3
106 */
107 @Override
108 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
109 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
110 if (appState == null || !appState.getModel().isModelLoaded()) {
111 return;
112 }
113 appState.getModel().dumpState("", fd, writer, args);
114 }
115
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116 @Override
117 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800118 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700119 Log.d(TAG, "Launcher process started");
120 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700121 mListenerHandler = new Handler(mListenerWrapper);
122
Sunny Goyalfdbef272017-02-01 12:52:54 -0800123 // The content provider exists for the entire duration of the launcher main process and
124 // is the first component to get created. Initializing FileLog here ensures that it's
125 // always available in the main process.
126 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700127 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700128 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800129 return true;
130 }
131
Sunny Goyald3849d12015-10-29 10:28:32 -0700132 /**
133 * Sets a provider listener.
134 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700135 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700136 Preconditions.assertUIThread();
137 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700138 }
139
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140 @Override
141 public String getType(Uri uri) {
142 SqlArguments args = new SqlArguments(uri, null, null);
143 if (TextUtils.isEmpty(args.where)) {
144 return "vnd.android.cursor.dir/" + args.table;
145 } else {
146 return "vnd.android.cursor.item/" + args.table;
147 }
148 }
149
Sunny Goyalf076eae2016-01-11 12:25:10 -0800150 /**
151 * Overridden in tests
152 */
153 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700154 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700155 if (LauncherAppState.PROFILE_STARTUP) {
156 Trace.beginSection("Opening workspace DB");
157 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700158 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700159
160 if (RestoreDbTask.isPending(getContext())) {
161 if (!RestoreDbTask.performRestore(mOpenHelper)) {
162 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
163 }
164 // Set is pending to false irrespective of the result, so that it doesn't get
165 // executed again.
166 RestoreDbTask.setPending(getContext(), false);
167 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700168
169 if (LauncherAppState.PROFILE_STARTUP) {
170 Trace.endSection();
171 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700172 }
173 }
174
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175 @Override
176 public Cursor query(Uri uri, String[] projection, String selection,
177 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700178 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179
180 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
181 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
182 qb.setTables(args.table);
183
Romain Guy73b979d2009-06-09 12:57:21 -0700184 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
186 result.setNotificationUri(getContext().getContentResolver(), uri);
187
188 return result;
189 }
190
Adam Cohen091440a2015-03-18 14:16:05 -0700191 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700192 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500193 if (values == null) {
194 throw new RuntimeException("Error: attempting to insert null values");
195 }
Adam Cohen71483f42014-05-15 14:04:01 -0700196 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700197 throw new RuntimeException("Error: attempting to add item without specifying an id");
198 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500199 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700200 return db.insert(table, nullColumnHack, values);
201 }
202
Sunny Goyald1064182015-08-13 12:08:30 -0700203 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700204 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700205 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
206 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800207 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700208 }
209 }
210 }
211
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 @Override
213 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700214 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215 SqlArguments args = new SqlArguments(uri);
216
Sunny Goyald1064182015-08-13 12:08:30 -0700217 // In very limited cases, we support system|signature permission apps to modify the db.
218 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700219 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700220 return null;
221 }
222 }
223
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400225 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700226 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800227 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800228
229 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700230 notifyListeners();
231
Sunny Goyalc74e4192015-09-08 14:01:03 -0700232 if (Utilities.ATLEAST_MARSHMALLOW) {
233 reloadLauncherIfExternal();
234 } else {
235 // Deprecated behavior to support legacy devices which rely on provider callbacks.
236 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
237 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800238 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700239 }
240
241 String notify = uri.getQueryParameter("notify");
242 if (notify == null || "true".equals(notify)) {
243 getContext().getContentResolver().notifyChange(uri, null);
244 }
245 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 return uri;
247 }
248
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700249 private boolean initializeExternalAdd(ContentValues values) {
250 // 1. Ensure that externally added items have a valid item id
251 long id = mOpenHelper.generateNewItemId();
252 values.put(LauncherSettings.Favorites._ID, id);
253
254 // 2. In the case of an app widget, and if no app widget id is specified, we
255 // attempt allocate and bind the widget.
256 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
257 if (itemType != null &&
258 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
259 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
260
261 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
262 ComponentName cn = ComponentName.unflattenFromString(
263 values.getAsString(Favorites.APPWIDGET_PROVIDER));
264
265 if (cn != null) {
266 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700267 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
268 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700269 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
270 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700271 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700272 return false;
273 }
274 } catch (RuntimeException e) {
275 Log.e(TAG, "Failed to initialize external widget", e);
276 return false;
277 }
278 } else {
279 return false;
280 }
281 }
282
283 // Add screen id if not present
284 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
285 SQLiteStatement stmp = null;
286 try {
287 stmp = mOpenHelper.getWritableDatabase().compileStatement(
288 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
289 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
290 stmp.bindLong(1, screenId);
291
292 ContentValues valuesInserted = new ContentValues();
293 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
294 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
295 return true;
296 } catch (Exception e) {
297 return false;
298 } finally {
299 Utilities.closeSilently(stmp);
300 }
301 }
302
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 @Override
304 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700305 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 SqlArguments args = new SqlArguments(uri);
307
308 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700309 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 int numValues = values.length;
311 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700313 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
314 return 0;
315 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800316 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700317 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318 }
319
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700320 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700321 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 return values.length;
323 }
324
325 @Override
Yura085c8532014-02-11 15:15:29 +0000326 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
327 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700328 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700329 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000330 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700331 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700332 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000333 return result;
Yura085c8532014-02-11 15:15:29 +0000334 }
335 }
336
337 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700339 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
341
342 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343
Louis Begina9c21c62016-08-15 15:18:41 -0700344 if (Binder.getCallingPid() != Process.myPid()
345 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700346 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700347 }
348 int count = db.delete(args.table, args.where, args.args);
349 if (count > 0) {
350 notifyListeners();
351 reloadLauncherIfExternal();
352 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800353 return count;
354 }
355
356 @Override
357 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700358 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
360
Chris Wren1ada10d2013-09-13 18:01:38 -0400361 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800362 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
363 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700364 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800365
Sunny Goyald1064182015-08-13 12:08:30 -0700366 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 return count;
368 }
369
Sunny Goyal7779d622015-06-11 16:18:39 -0700370 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700371 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700372 if (Binder.getCallingUid() != Process.myUid()) {
373 return null;
374 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700375 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700376
377 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700378 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
379 String extractedColors = extras.getString(
380 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
381 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
382 Utilities.getPrefs(getContext()).edit()
383 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
384 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
385 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700386 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700387 Bundle result = new Bundle();
388 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
389 return result;
390 }
Sunny Goyald2497482015-09-22 18:24:19 -0700391 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
392 clearFlagEmptyDbCreated();
393 return null;
394 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700395 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
396 Bundle result = new Bundle();
397 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
398 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
399 return result;
400 }
Sunny Goyald2497482015-09-22 18:24:19 -0700401 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
402 Bundle result = new Bundle();
403 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
404 return result;
405 }
406 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
407 Bundle result = new Bundle();
408 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
409 return result;
410 }
411 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
412 Bundle result = new Bundle();
413 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
414 return result;
415 }
416 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800417 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700418 return null;
419 }
420 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
421 loadDefaultFavoritesIfNecessary();
422 return null;
423 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700424 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
425 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
426 return null;
427 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700428 }
429 return null;
430 }
431
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 /**
433 * Deletes any empty folder from the DB.
434 * @return Ids of deleted folders.
435 */
Sunny Goyald2497482015-09-22 18:24:19 -0700436 private ArrayList<Long> deleteEmptyFolders() {
437 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700438 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700439 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700440 // Select folders whose id do not match any container value.
441 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
442 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
443 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
444 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700445 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700446 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700447 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700448 selection, null, null, null, null)) {
449 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700450 }
Sunny Goyald2497482015-09-22 18:24:19 -0700451 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700452 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700453 LauncherSettings.Favorites._ID, folderIds), null);
454 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700455 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700456 } catch (SQLException ex) {
457 Log.e(TAG, ex.getMessage(), ex);
458 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700459 }
460 return folderIds;
461 }
462
Sunny Goyalf076eae2016-01-11 12:25:10 -0800463 /**
464 * Overridden in tests
465 */
466 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700467 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 }
469
Adam Cohen091440a2015-03-18 14:16:05 -0700470 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400471 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 }
473
Sunny Goyald2497482015-09-22 18:24:19 -0700474 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700475 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700476 }
477
Sunny Goyal42de82f2014-09-26 22:09:29 -0700478 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700480 * 1) From the app restrictions
481 * 2) From a package provided by play store
482 * 3) From a partner configuration APK, already in the system image
483 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700484 */
Sunny Goyald2497482015-09-22 18:24:19 -0700485 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700486 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700487
Winson Chungc763c4e2013-07-19 13:49:06 -0700488 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500489 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200490
Sunny Goyal55fddc82017-04-06 15:02:52 -0700491 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700492 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700493 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700494 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700495 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700496 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700497 final Partner partner = Partner.get(getContext().getPackageManager());
498 if (partner != null && partner.hasDefaultLayout()) {
499 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700500 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700501 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700503 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700504 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700505 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700506 }
507 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700508
Sunny Goyal9d219682014-10-23 14:21:02 -0700509 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700510 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700511 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700512 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800513
514 // There might be some partially restored DB items, due to buggy restore logic in
515 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800516 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700517 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700518 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
519 && usingExternallyProvidedLayout) {
520 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800521 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700522 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700523 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700524 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700525 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700526 }
527 }
528
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700529 /**
530 * Creates workspace loader from an XML resource listed in the app restrictions.
531 *
532 * @return the loader if the restrictions are set and the resource exists; null otherwise.
533 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700535 Context ctx = getContext();
536 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
537 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700538 if (bundle == null) {
539 return null;
540 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541
Sunny Goyal35ca8732015-04-06 10:45:31 -0700542 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700543 if (packageName != null) {
544 try {
545 Resources targetResources = ctx.getPackageManager()
546 .getResourcesForApplication(packageName);
547 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700549 } catch (NameNotFoundException e) {
550 Log.e(TAG, "Target package for restricted profile not found", e);
551 return null;
552 }
553 }
554 return null;
555 }
556
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800558 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700559 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700560 mOpenHelper, getContext().getResources(), defaultLayout);
561 }
562
Sunny Goyald3849d12015-10-29 10:28:32 -0700563 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800564 * The class is subclassed in tests to create an in-memory db.
565 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700566 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700567 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800568 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700569 private long mMaxItemId = -1;
570 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800571
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700572 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
573 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700574 // Table creation sometimes fails silently, which leads to a crash loop.
575 // This way, we will try to create a table every time after crash, so the device
576 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700577 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700578 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
579 // This operation is a no-op if the table already exists.
580 addFavoritesTable(getWritableDatabase(), true);
581 addWorkspacesTable(getWritableDatabase(), true);
582 }
583
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700584 initIds();
585 }
586
587 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700588 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700589 */
590 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700591 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700592 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700593 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700594 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700595 }
596
597 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700598 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
599 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700600 if (mMaxItemId == -1) {
601 mMaxItemId = initializeMaxItemId(getWritableDatabase());
602 }
603 if (mMaxScreenId == -1) {
604 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700605 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 }
607
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700608 private boolean tableExists(String tableName) {
609 Cursor c = getReadableDatabase().query(
610 true, "sqlite_master", new String[] {"tbl_name"},
611 "tbl_name = ?", new String[] {tableName},
612 null, null, null, null, null);
613 try {
614 return c.getCount() > 0;
615 } finally {
616 c.close();
617 }
618 }
619
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 @Override
621 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800622 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700623
Adam Cohendcd297f2013-06-18 13:13:40 -0700624 mMaxItemId = 1;
625 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700626
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700627 addFavoritesTable(db, false);
628 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800630 // Fresh and clean launcher DB.
631 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800632 onEmptyDbCreated();
633 }
634
635 /**
636 * Overriden in tests.
637 */
638 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700639 // Database was just created, so wipe any previous widgets
640 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700641 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700642 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530643 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700644 }
645
Sunny Goyalf076eae2016-01-11 12:25:10 -0800646 // Set the flag for empty DB
647 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700648
649 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800650 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800651 mContext);
652 }
653
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700654 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800655 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800656 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800657 }
658
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700659 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700660 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700661 }
662
663 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
664 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700665 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800666 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400667 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
668 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700669 ");");
670 }
671
Adam Cohen119285e2014-04-02 16:59:08 -0700672 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 // Delete items directly on the workspace who's screen id doesn't exist
674 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
675 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700676 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700677 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700678 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700679 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700680 " AND " +
681 LauncherSettings.Favorites.CONTAINER + " = " +
682 LauncherSettings.Favorites.CONTAINER_DESKTOP;
683 db.execSQL(removeOrphanedDesktopItems);
684
685 // Delete items contained in folders which no longer exist (after above statement)
686 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
687 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700688 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700689 " WHERE " +
690 LauncherSettings.Favorites.CONTAINER + " <> " +
691 LauncherSettings.Favorites.CONTAINER_DESKTOP +
692 " AND "
693 + LauncherSettings.Favorites.CONTAINER + " <> " +
694 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
695 " AND "
696 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700697 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700698 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
699 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
700 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700701 }
702
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800703 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700704 public void onOpen(SQLiteDatabase db) {
705 super.onOpen(db);
706 SharedPreferences prefs = mContext
707 .getSharedPreferences(LauncherFiles.DEVICE_PREFERENCES_KEY, 0);
708 int oldVersion = prefs.getInt(PREF_KEY_DATA_VERISON, 0);
709 if (oldVersion != DATA_VERSION) {
710 // Only run the data upgrade path for an existing db.
711 if (!Utilities.getPrefs(mContext).getBoolean(EMPTY_DATABASE_CREATED, false)) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700712 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700713 onDataUpgrade(db, oldVersion);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700714 t.commit();
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700715 } catch (Exception e) {
716 Log.d(TAG, "Error updating data version, ignoring", e);
717 return;
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700718 }
719 }
720 prefs.edit().putInt(PREF_KEY_DATA_VERISON, DATA_VERSION).apply();
721 }
722 }
723
724 /**
725 * Called when the data is updated as part of app update. It can be called multiple times
726 * with old version, even though it had been run before. The changes made here must be
727 * backwards compatible, else we risk breaking old devices during restore or binary
728 * version downgrade.
729 */
730 protected void onDataUpgrade(SQLiteDatabase db, int oldVersion) {
731 switch (oldVersion) {
732 case 0:
733 case 1: {
734 // Remove "profile extra"
735 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
736 for (UserHandle user : um.getUserProfiles()) {
737 long serial = um.getSerialNumberForUser(user);
738 String sql = "update favorites set intent = replace(intent, "
739 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
740 db.execSQL(sql);
741 }
742 }
743 case 2:
Sunny Goyal55fddc82017-04-06 15:02:52 -0700744 case 3:
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700745 // data updated
746 return;
747 }
748 }
749
750 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800751 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700752 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 switch (oldVersion) {
754 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800755 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800756 case 12: {
757 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
758 // to persist workspace screens and their relative order.
759 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700760 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 }
762 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700763 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 // Insert new column for holding widget provider name
765 db.execSQL("ALTER TABLE favorites " +
766 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700767 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800768 } catch (SQLException ex) {
769 Log.e(TAG, ex.getMessage(), ex);
770 // Old version remains, which means we wipe old data
771 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800772 }
773 }
774 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700775 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800776 // Insert new column for holding update timestamp
777 db.execSQL("ALTER TABLE favorites " +
778 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
779 db.execSQL("ALTER TABLE workspaceScreens " +
780 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700781 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800782 } catch (SQLException ex) {
783 Log.e(TAG, ex.getMessage(), ex);
784 // Old version remains, which means we wipe old data
785 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800786 }
787 }
788 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700789 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800790 // Old version remains, which means we wipe old data
791 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800792 }
793 }
794 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700795 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800796 }
797 case 17: {
798 // No-op
799 }
800 case 18: {
801 // Due to a data loss bug, some users may have items associated with screen ids
802 // which no longer exist. Since this can cause other problems, and since the user
803 // will never see these items anyway, we use database upgrade as an opportunity to
804 // clean things up.
805 removeOrphanedItems(db);
806 }
807 case 19: {
808 // Add userId column
809 if (!addProfileColumn(db)) {
810 // Old version remains, which means we wipe old data
811 break;
812 }
813 }
814 case 20:
815 if (!updateFolderItemsRank(db, true)) {
816 break;
817 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800818 case 21:
819 // Recreate workspace table with screen id a primary key
820 if (!recreateWorkspaceTable(db)) {
821 break;
822 }
823 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700824 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
825 // Old version remains, which means we wipe old data
826 break;
827 }
828 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700829 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700830 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700831 case 24:
832 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700833 case 25:
834 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700835 case 26:
836 // QSB was moved to the grid. Clear the first row on screen 0.
837 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800838 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700839 break;
840 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700841 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800842 // DB Upgraded successfully
843 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400844 }
845
Sunny Goyala2cc6242015-01-14 14:23:02 -0800846 // DB was not upgraded
847 Log.w(TAG, "Destroying all old data.");
848 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800849 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800850
Adam Cohen9b1d0622014-05-21 19:01:57 -0700851 @Override
852 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700853 if (oldVersion == 28 && newVersion == 27) {
854 // TODO: remove this check. This is only applicable for internal development/testing
855 // and for any released version of Launcher.
856 return;
857 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700858 // This shouldn't happen -- throw our hands up in the air and start over.
859 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
860 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700861 createEmptyDB(db);
862 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700863
Sunny Goyal42de82f2014-09-26 22:09:29 -0700864 /**
865 * Clears all the data for a fresh start.
866 */
867 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700868 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800869 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
870 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
871 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700872 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800873 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700874 }
875
Sunny Goyald2f38192015-02-25 10:46:34 -0800876 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700877 * Removes widgets which are registered to the Launcher's host, but are not present
878 * in our model.
879 */
880 public void removeGhostWidgets(SQLiteDatabase db) {
881 // Get all existing widget ids.
882 final AppWidgetHost host = newLauncherWidgetHost();
883 final int[] allWidgets;
884 try {
885 Method getter = AppWidgetHost.class.getDeclaredMethod("getAppWidgetIds");
886 getter.setAccessible(true);
887 allWidgets = (int[]) getter.invoke(host);
888 } catch (Exception e) {
889 Log.e(TAG, "getAppWidgetIds not supported", e);
890 return;
891 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700892 final HashSet<Integer> validWidgets = new HashSet<>();
893 try (Cursor c = db.query(Favorites.TABLE_NAME,
894 new String[] {Favorites.APPWIDGET_ID },
895 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700896 while (c.moveToNext()) {
897 validWidgets.add(c.getInt(0));
898 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700899 } catch (SQLException ex) {
900 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700901 return;
902 }
903 for (int widgetId : allWidgets) {
904 if (!validWidgets.contains(widgetId)) {
905 try {
906 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
907 host.deleteAppWidgetId(widgetId);
908 } catch (RuntimeException e) {
909 // Ignore
910 }
911 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700912 }
913 }
914
915 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700916 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
917 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
918 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700919 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700920 try (SQLiteTransaction t = new SQLiteTransaction(db);
921 // Only consider the primary user as other users can't have a shortcut.
922 Cursor c = db.query(Favorites.TABLE_NAME,
923 new String[] { Favorites._ID, Favorites.INTENT},
924 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
925 " AND profileId=" + getDefaultUserSerial(),
926 null, null, null, null);
927 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
928 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
929 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700930 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
931 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
932
933 while (c.moveToNext()) {
934 String intentDescription = c.getString(intentIndex);
935 Intent intent;
936 try {
937 intent = Intent.parseUri(intentDescription, 0);
938 } catch (URISyntaxException e) {
939 Log.e(TAG, "Unable to parse intent", e);
940 continue;
941 }
942
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700943 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700944 continue;
945 }
946
947 long id = c.getLong(idIndex);
948 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700949 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700950 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700951 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700952 } catch (SQLException ex) {
953 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700954 }
955 }
956
957 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800958 * Recreates workspace table and migrates data to the new table.
959 */
960 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700961 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
962 final ArrayList<Long> sortedIDs;
963
964 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800965 new String[] {LauncherSettings.WorkspaceScreens._ID},
966 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700967 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
968 // Use LinkedHashSet so that ordering is preserved
969 sortedIDs = new ArrayList<>(
970 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800971 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700972 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700973 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800974
975 // Add all screen ids back
976 int total = sortedIDs.size();
977 for (int i = 0; i < total; i++) {
978 ContentValues values = new ContentValues();
979 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
980 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
981 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700982 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800983 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700984 t.commit();
985 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800986 } catch (SQLException ex) {
987 // Old version remains, which means we wipe old data
988 Log.e(TAG, ex.getMessage(), ex);
989 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800990 }
991 return true;
992 }
993
Adam Cohen091440a2015-03-18 14:16:05 -0700994 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700995 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800996 if (addRankColumn) {
997 // Insert new column for holding rank
998 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
999 }
1000
1001 // Get a map for folder ID to folder width
1002 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1003 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1004 + " GROUP BY container;",
1005 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1006
1007 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001008 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1009 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001010 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1011 }
1012
1013 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001014 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001015 } catch (SQLException ex) {
1016 // Old version remains, which means we wipe old data
1017 Log.e(TAG, ex.getMessage(), ex);
1018 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001019 }
1020 return true;
1021 }
1022
Kenny Guyed131872014-04-30 03:02:21 +01001023 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001024 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -07001025 }
1026
1027 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001028 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001029 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1030 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001031 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001032 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001033 Log.e(TAG, ex.getMessage(), ex);
1034 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001035 }
1036 return true;
1037 }
1038
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039 // Generates a new ID to use for an object in your database. This method should be only
1040 // called from the main UI thread. As an exception, we do call it when we call the
1041 // constructor from the worker thread; however, this doesn't extend until after the
1042 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1043 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001044 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001045 public long generateNewItemId() {
1046 if (mMaxItemId < 0) {
1047 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001048 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 mMaxItemId += 1;
1050 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001051 }
1052
Sunny Goyal55fddc82017-04-06 15:02:52 -07001053 public AppWidgetHost newLauncherWidgetHost() {
1054 return new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID);
1055 }
1056
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001057 @Override
1058 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001059 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001060 }
1061
Chris Wren5dee7af2013-12-20 17:22:11 -05001062 public void checkId(String table, ContentValues values) {
1063 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001064 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001065 mMaxScreenId = Math.max(id, mMaxScreenId);
1066 } else {
1067 mMaxItemId = Math.max(id, mMaxItemId);
1068 }
1069 }
1070
Adam Cohendcd297f2013-06-18 13:13:40 -07001071 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001072 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001073 }
1074
1075 // Generates a new ID to use for an workspace screen in your database. This method
1076 // should be only called from the main UI thread. As an exception, we do call it when we
1077 // call the constructor from the worker thread; however, this doesn't extend until after the
1078 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1079 // after that point
1080 public long generateNewScreenId() {
1081 if (mMaxScreenId < 0) {
1082 throw new RuntimeException("Error: max screen id was not initialized");
1083 }
1084 mMaxScreenId += 1;
1085 return mMaxScreenId;
1086 }
1087
Adam Cohendcd297f2013-06-18 13:13:40 -07001088 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001089 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001090 }
1091
Adam Cohen091440a2015-03-18 14:16:05 -07001092 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001093 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001094 // TODO: Use multiple loaders with fall-back and transaction.
1095 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001096
1097 // Add the screens specified by the items above
1098 Collections.sort(screenIds);
1099 int rank = 0;
1100 ContentValues values = new ContentValues();
1101 for (Long id : screenIds) {
1102 values.clear();
1103 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1104 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001105 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001106 throw new RuntimeException("Failed initialize screen table"
1107 + "from default layout");
1108 }
1109 rank++;
1110 }
1111
1112 // Ensure that the max ids are initialized
1113 mMaxItemId = initializeMaxItemId(db);
1114 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001115
Adam Cohen71483f42014-05-15 14:04:01 -07001116 return count;
1117 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001118 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001119
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001120 /**
1121 * @return the max _id in the provided table.
1122 */
Adam Cohen091440a2015-03-18 14:16:05 -07001123 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001124 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1125 // get the result
1126 long id = -1;
1127 if (c != null && c.moveToNext()) {
1128 id = c.getLong(0);
1129 }
1130 if (c != null) {
1131 c.close();
1132 }
1133
1134 if (id == -1) {
1135 throw new RuntimeException("Error: could not query max id in " + table);
1136 }
1137
1138 return id;
1139 }
1140
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001141 static class SqlArguments {
1142 public final String table;
1143 public final String where;
1144 public final String[] args;
1145
1146 SqlArguments(Uri url, String where, String[] args) {
1147 if (url.getPathSegments().size() == 1) {
1148 this.table = url.getPathSegments().get(0);
1149 this.where = where;
1150 this.args = args;
1151 } else if (url.getPathSegments().size() != 2) {
1152 throw new IllegalArgumentException("Invalid URI: " + url);
1153 } else if (!TextUtils.isEmpty(where)) {
1154 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1155 } else {
1156 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001157 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001158 this.args = null;
1159 }
1160 }
1161
1162 SqlArguments(Uri url) {
1163 if (url.getPathSegments().size() == 1) {
1164 table = url.getPathSegments().get(0);
1165 where = null;
1166 args = null;
1167 } else {
1168 throw new IllegalArgumentException("Invalid URI: " + url);
1169 }
1170 }
1171 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001172
1173 private static class ChangeListenerWrapper implements Handler.Callback {
1174
1175 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1176 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1177 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1178
1179 private LauncherProviderChangeListener mListener;
1180
1181 @Override
1182 public boolean handleMessage(Message msg) {
1183 if (mListener != null) {
1184 switch (msg.what) {
1185 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001186 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001187 break;
1188 case MSG_EXTRACTED_COLORS_CHANGED:
1189 mListener.onExtractedColorsChanged();
1190 break;
1191 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001192 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001193 break;
1194 }
1195 }
1196 return true;
1197 }
1198 }
Adam Cohen72960972014-01-15 18:13:55 -08001199}