blob: 7bfa70c7ef54deff75690b47baa0caa959d943fd [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
35import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteOpenHelper;
38import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070042import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070047import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080048import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070049import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070052
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
54import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070055import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070057import com.android.launcher3.config.FeatureFlags;
Tony Wickham827cef22016-03-17 15:39:39 -070058import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyalca187462017-03-31 20:09:34 -070059import com.android.launcher3.graphics.IconShapeOverride;
Sunny Goyalfdbef272017-02-01 12:52:54 -080060import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070061import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070062import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070063import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070064import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070065import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070066import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070067import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070068import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070069
Sunny Goyal05f30882017-05-03 12:42:18 -070070import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080071import java.io.FileDescriptor;
72import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070073import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070074import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070075import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070076import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070077import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070080 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080081 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
Sunny Goyal05f30882017-05-03 12:42:18 -070083 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
84
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070085 /**
86 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
87 */
Sunny Goyal05f30882017-05-03 12:42:18 -070088 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
Sunny Goyal3d706ad2017-03-06 16:56:39 -080090 public static final String AUTHORITY = (BuildConfig.APPLICATION_ID + ".settings").intern();
Winson Chung3d503fb2011-07-13 17:25:49 -070091
Sunny Goyale87e6ab2014-11-21 22:42:53 -080092 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070094 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
95
Sunny Goyalb5b55c82016-05-10 12:28:59 -070096 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
97 private Handler mListenerHandler;
98
Sunny Goyalf076eae2016-01-11 12:25:10 -080099 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800101 /**
102 * $ adb shell dumpsys activity provider com.android.launcher3
103 */
104 @Override
105 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
106 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
107 if (appState == null || !appState.getModel().isModelLoaded()) {
108 return;
109 }
110 appState.getModel().dumpState("", fd, writer, args);
111 }
112
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113 @Override
114 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800115 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700116 Log.d(TAG, "Launcher process started");
117 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700118 mListenerHandler = new Handler(mListenerWrapper);
119
Sunny Goyalfdbef272017-02-01 12:52:54 -0800120 // The content provider exists for the entire duration of the launcher main process and
121 // is the first component to get created. Initializing FileLog here ensures that it's
122 // always available in the main process.
123 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700124 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700125 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126 return true;
127 }
128
Sunny Goyald3849d12015-10-29 10:28:32 -0700129 /**
130 * Sets a provider listener.
131 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700132 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700133 Preconditions.assertUIThread();
134 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700135 }
136
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137 @Override
138 public String getType(Uri uri) {
139 SqlArguments args = new SqlArguments(uri, null, null);
140 if (TextUtils.isEmpty(args.where)) {
141 return "vnd.android.cursor.dir/" + args.table;
142 } else {
143 return "vnd.android.cursor.item/" + args.table;
144 }
145 }
146
Sunny Goyalf076eae2016-01-11 12:25:10 -0800147 /**
148 * Overridden in tests
149 */
150 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700151 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700152 if (LauncherAppState.PROFILE_STARTUP) {
153 Trace.beginSection("Opening workspace DB");
154 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700155 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700156
157 if (RestoreDbTask.isPending(getContext())) {
158 if (!RestoreDbTask.performRestore(mOpenHelper)) {
159 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
160 }
161 // Set is pending to false irrespective of the result, so that it doesn't get
162 // executed again.
163 RestoreDbTask.setPending(getContext(), false);
164 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700165
166 if (LauncherAppState.PROFILE_STARTUP) {
167 Trace.endSection();
168 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700169 }
170 }
171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 @Override
173 public Cursor query(Uri uri, String[] projection, String selection,
174 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700175 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
178 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
179 qb.setTables(args.table);
180
Romain Guy73b979d2009-06-09 12:57:21 -0700181 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
183 result.setNotificationUri(getContext().getContentResolver(), uri);
184
185 return result;
186 }
187
Adam Cohen091440a2015-03-18 14:16:05 -0700188 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700189 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500190 if (values == null) {
191 throw new RuntimeException("Error: attempting to insert null values");
192 }
Adam Cohen71483f42014-05-15 14:04:01 -0700193 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700194 throw new RuntimeException("Error: attempting to add item without specifying an id");
195 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500196 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700197 return db.insert(table, nullColumnHack, values);
198 }
199
Sunny Goyald1064182015-08-13 12:08:30 -0700200 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700201 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700202 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
203 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800204 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700205 }
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 @Override
210 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700211 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 SqlArguments args = new SqlArguments(uri);
213
Sunny Goyald1064182015-08-13 12:08:30 -0700214 // In very limited cases, we support system|signature permission apps to modify the db.
215 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700216 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700217 return null;
218 }
219 }
220
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400222 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700223 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800224 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225
226 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700227 notifyListeners();
228
Sunny Goyalc74e4192015-09-08 14:01:03 -0700229 if (Utilities.ATLEAST_MARSHMALLOW) {
230 reloadLauncherIfExternal();
231 } else {
232 // Deprecated behavior to support legacy devices which rely on provider callbacks.
233 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
234 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800235 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700236 }
237
238 String notify = uri.getQueryParameter("notify");
239 if (notify == null || "true".equals(notify)) {
240 getContext().getContentResolver().notifyChange(uri, null);
241 }
242 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800243 return uri;
244 }
245
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700246 private boolean initializeExternalAdd(ContentValues values) {
247 // 1. Ensure that externally added items have a valid item id
248 long id = mOpenHelper.generateNewItemId();
249 values.put(LauncherSettings.Favorites._ID, id);
250
251 // 2. In the case of an app widget, and if no app widget id is specified, we
252 // attempt allocate and bind the widget.
253 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
254 if (itemType != null &&
255 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
256 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
257
258 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
259 ComponentName cn = ComponentName.unflattenFromString(
260 values.getAsString(Favorites.APPWIDGET_PROVIDER));
261
262 if (cn != null) {
263 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700264 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
265 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700266 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
267 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700268 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700269 return false;
270 }
271 } catch (RuntimeException e) {
272 Log.e(TAG, "Failed to initialize external widget", e);
273 return false;
274 }
275 } else {
276 return false;
277 }
278 }
279
280 // Add screen id if not present
281 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
282 SQLiteStatement stmp = null;
283 try {
284 stmp = mOpenHelper.getWritableDatabase().compileStatement(
285 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
286 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
287 stmp.bindLong(1, screenId);
288
289 ContentValues valuesInserted = new ContentValues();
290 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
291 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
292 return true;
293 } catch (Exception e) {
294 return false;
295 } finally {
296 Utilities.closeSilently(stmp);
297 }
298 }
299
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 @Override
301 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700302 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 SqlArguments args = new SqlArguments(uri);
304
305 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700306 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 int numValues = values.length;
308 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400309 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700310 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
311 return 0;
312 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700314 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 }
316
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700317 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700318 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800319 return values.length;
320 }
321
322 @Override
Yura085c8532014-02-11 15:15:29 +0000323 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
324 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700325 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700326 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000327 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700328 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700329 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000330 return result;
Yura085c8532014-02-11 15:15:29 +0000331 }
332 }
333
334 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700336 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
338
339 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340
Louis Begina9c21c62016-08-15 15:18:41 -0700341 if (Binder.getCallingPid() != Process.myPid()
342 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700343 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700344 }
345 int count = db.delete(args.table, args.where, args.args);
346 if (count > 0) {
347 notifyListeners();
348 reloadLauncherIfExternal();
349 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 return count;
351 }
352
353 @Override
354 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700355 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
357
Chris Wren1ada10d2013-09-13 18:01:38 -0400358 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
360 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700361 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800362
Sunny Goyald1064182015-08-13 12:08:30 -0700363 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800364 return count;
365 }
366
Sunny Goyal7779d622015-06-11 16:18:39 -0700367 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700368 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700369 if (Binder.getCallingUid() != Process.myUid()) {
370 return null;
371 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700372 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700373
374 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700375 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
376 String extractedColors = extras.getString(
377 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
378 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
379 Utilities.getPrefs(getContext()).edit()
380 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
381 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
382 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700383 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700384 Bundle result = new Bundle();
385 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
386 return result;
387 }
Sunny Goyald2497482015-09-22 18:24:19 -0700388 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
389 clearFlagEmptyDbCreated();
390 return null;
391 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700392 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
393 Bundle result = new Bundle();
394 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
395 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
396 return result;
397 }
Sunny Goyald2497482015-09-22 18:24:19 -0700398 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
399 Bundle result = new Bundle();
400 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
401 return result;
402 }
403 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
404 Bundle result = new Bundle();
405 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
406 return result;
407 }
408 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
409 Bundle result = new Bundle();
410 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
411 return result;
412 }
413 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800414 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700415 return null;
416 }
417 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
418 loadDefaultFavoritesIfNecessary();
419 return null;
420 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700421 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
422 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
423 return null;
424 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700425 }
426 return null;
427 }
428
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 /**
430 * Deletes any empty folder from the DB.
431 * @return Ids of deleted folders.
432 */
Sunny Goyald2497482015-09-22 18:24:19 -0700433 private ArrayList<Long> deleteEmptyFolders() {
434 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700435 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700436 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700437 // Select folders whose id do not match any container value.
438 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
439 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
440 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
441 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700442 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700443 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700444 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700445 selection, null, null, null, null)) {
446 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700447 }
Sunny Goyald2497482015-09-22 18:24:19 -0700448 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700449 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700450 LauncherSettings.Favorites._ID, folderIds), null);
451 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700452 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700453 } catch (SQLException ex) {
454 Log.e(TAG, ex.getMessage(), ex);
455 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700456 }
457 return folderIds;
458 }
459
Sunny Goyalf076eae2016-01-11 12:25:10 -0800460 /**
461 * Overridden in tests
462 */
463 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700464 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400465 }
466
Adam Cohen091440a2015-03-18 14:16:05 -0700467 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 }
470
Sunny Goyald2497482015-09-22 18:24:19 -0700471 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700472 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700473 }
474
Sunny Goyal42de82f2014-09-26 22:09:29 -0700475 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700476 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700477 * 1) From the app restrictions
478 * 2) From a package provided by play store
479 * 3) From a partner configuration APK, already in the system image
480 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700481 */
Sunny Goyald2497482015-09-22 18:24:19 -0700482 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700483 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700484
Winson Chungc763c4e2013-07-19 13:49:06 -0700485 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500486 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200487
Sunny Goyal55fddc82017-04-06 15:02:52 -0700488 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700489 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700490 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700491 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700492 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700493 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700494 final Partner partner = Partner.get(getContext().getPackageManager());
495 if (partner != null && partner.hasDefaultLayout()) {
496 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700497 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700498 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700499 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700500 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700501 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700503 }
504 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700505
Sunny Goyal9d219682014-10-23 14:21:02 -0700506 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700507 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700508 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700509 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800510
511 // There might be some partially restored DB items, due to buggy restore logic in
512 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800513 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700514 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700515 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
516 && usingExternallyProvidedLayout) {
517 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800518 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700519 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700520 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700521 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700522 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700523 }
524 }
525
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526 /**
527 * Creates workspace loader from an XML resource listed in the app restrictions.
528 *
529 * @return the loader if the restrictions are set and the resource exists; null otherwise.
530 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700531 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700532 Context ctx = getContext();
533 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
534 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700535 if (bundle == null) {
536 return null;
537 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700538
Sunny Goyal35ca8732015-04-06 10:45:31 -0700539 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700540 if (packageName != null) {
541 try {
542 Resources targetResources = ctx.getPackageManager()
543 .getResourcesForApplication(packageName);
544 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700546 } catch (NameNotFoundException e) {
547 Log.e(TAG, "Target package for restricted profile not found", e);
548 return null;
549 }
550 }
551 return null;
552 }
553
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700554 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700555 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
556 int defaultLayout = idp.defaultLayoutId;
557
558 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
559 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
560 defaultLayout = idp.demoModeLayoutId;
561 }
562
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700563 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700564 mOpenHelper, getContext().getResources(), defaultLayout);
565 }
566
Sunny Goyald3849d12015-10-29 10:28:32 -0700567 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800568 * The class is subclassed in tests to create an in-memory db.
569 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700570 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700571 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 private long mMaxItemId = -1;
574 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700576 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
577 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700578 // Table creation sometimes fails silently, which leads to a crash loop.
579 // This way, we will try to create a table every time after crash, so the device
580 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700581 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700582 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
583 // This operation is a no-op if the table already exists.
584 addFavoritesTable(getWritableDatabase(), true);
585 addWorkspacesTable(getWritableDatabase(), true);
586 }
587
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700588 initIds();
589 }
590
591 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700592 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700593 */
594 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700595 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700596 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700597 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700598 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700599 }
600
601 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700602 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
603 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700604 if (mMaxItemId == -1) {
605 mMaxItemId = initializeMaxItemId(getWritableDatabase());
606 }
607 if (mMaxScreenId == -1) {
608 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700609 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610 }
611
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700612 private boolean tableExists(String tableName) {
613 Cursor c = getReadableDatabase().query(
614 true, "sqlite_master", new String[] {"tbl_name"},
615 "tbl_name = ?", new String[] {tableName},
616 null, null, null, null, null);
617 try {
618 return c.getCount() > 0;
619 } finally {
620 c.close();
621 }
622 }
623
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 @Override
625 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800626 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700627
Adam Cohendcd297f2013-06-18 13:13:40 -0700628 mMaxItemId = 1;
629 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700630
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700631 addFavoritesTable(db, false);
632 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800634 // Fresh and clean launcher DB.
635 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800636 onEmptyDbCreated();
637 }
638
639 /**
640 * Overriden in tests.
641 */
642 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700643 // Database was just created, so wipe any previous widgets
644 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700645 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700646 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530647 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700648 }
649
Sunny Goyalf076eae2016-01-11 12:25:10 -0800650 // Set the flag for empty DB
651 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700652
653 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800654 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800655 mContext);
656 }
657
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700658 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800659 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800660 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800661 }
662
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700663 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700664 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700665 }
666
667 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
668 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700669 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800670 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400671 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
672 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 ");");
674 }
675
Adam Cohen119285e2014-04-02 16:59:08 -0700676 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700677 // Delete items directly on the workspace who's screen id doesn't exist
678 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
679 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700680 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700681 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700682 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700683 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700684 " AND " +
685 LauncherSettings.Favorites.CONTAINER + " = " +
686 LauncherSettings.Favorites.CONTAINER_DESKTOP;
687 db.execSQL(removeOrphanedDesktopItems);
688
689 // Delete items contained in folders which no longer exist (after above statement)
690 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
691 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700692 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700693 " WHERE " +
694 LauncherSettings.Favorites.CONTAINER + " <> " +
695 LauncherSettings.Favorites.CONTAINER_DESKTOP +
696 " AND "
697 + LauncherSettings.Favorites.CONTAINER + " <> " +
698 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
699 " AND "
700 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700701 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700702 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
703 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
704 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700705 }
706
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700708 public void onOpen(SQLiteDatabase db) {
709 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700710
711 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
712 if (!schemaFile.exists()) {
713 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700714 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700715 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
716 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700717 }
718
719 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700720 * One-time data updated before support of onDowngrade was added. This update is backwards
721 * compatible and can safely be run multiple times.
722 * Note: No new logic should be added here after release, as the new logic might not get
723 * executed on an existing device.
724 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700725 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700726 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
727 // Remove "profile extra"
728 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
729 for (UserHandle user : um.getUserProfiles()) {
730 long serial = um.getSerialNumberForUser(user);
731 String sql = "update favorites set intent = replace(intent, "
732 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
733 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700734 }
735 }
736
737 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800738 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700739 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800740 switch (oldVersion) {
741 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800742 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 case 12: {
744 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
745 // to persist workspace screens and their relative order.
746 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700747 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 }
749 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700750 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 // Insert new column for holding widget provider name
752 db.execSQL("ALTER TABLE favorites " +
753 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700754 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 } catch (SQLException ex) {
756 Log.e(TAG, ex.getMessage(), ex);
757 // Old version remains, which means we wipe old data
758 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 }
760 }
761 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700762 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800763 // Insert new column for holding update timestamp
764 db.execSQL("ALTER TABLE favorites " +
765 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
766 db.execSQL("ALTER TABLE workspaceScreens " +
767 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700768 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800769 } catch (SQLException ex) {
770 Log.e(TAG, ex.getMessage(), ex);
771 // Old version remains, which means we wipe old data
772 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800773 }
774 }
775 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700776 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800777 // Old version remains, which means we wipe old data
778 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800779 }
780 }
781 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700782 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800783 }
784 case 17: {
785 // No-op
786 }
787 case 18: {
788 // Due to a data loss bug, some users may have items associated with screen ids
789 // which no longer exist. Since this can cause other problems, and since the user
790 // will never see these items anyway, we use database upgrade as an opportunity to
791 // clean things up.
792 removeOrphanedItems(db);
793 }
794 case 19: {
795 // Add userId column
796 if (!addProfileColumn(db)) {
797 // Old version remains, which means we wipe old data
798 break;
799 }
800 }
801 case 20:
802 if (!updateFolderItemsRank(db, true)) {
803 break;
804 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800805 case 21:
806 // Recreate workspace table with screen id a primary key
807 if (!recreateWorkspaceTable(db)) {
808 break;
809 }
810 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700811 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
812 // Old version remains, which means we wipe old data
813 break;
814 }
815 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700817 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700818 case 24:
819 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700820 case 25:
821 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700822 case 26:
823 // QSB was moved to the grid. Clear the first row on screen 0.
824 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800825 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700826 break;
827 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700828 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800829 // DB Upgraded successfully
830 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400831 }
832
Sunny Goyala2cc6242015-01-14 14:23:02 -0800833 // DB was not upgraded
834 Log.w(TAG, "Destroying all old data.");
835 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800836 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800837
Adam Cohen9b1d0622014-05-21 19:01:57 -0700838 @Override
839 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700840 try {
841 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
842 .onDowngrade(db, oldVersion, newVersion);
843 } catch (Exception e) {
844 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
845 ". Wiping databse.", e);
846 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700847 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700848 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700849
Sunny Goyal42de82f2014-09-26 22:09:29 -0700850 /**
851 * Clears all the data for a fresh start.
852 */
853 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700854 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800855 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
856 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
857 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700858 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800859 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700860 }
861
Sunny Goyald2f38192015-02-25 10:46:34 -0800862 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700863 * Removes widgets which are registered to the Launcher's host, but are not present
864 * in our model.
865 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700866 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700867 public void removeGhostWidgets(SQLiteDatabase db) {
868 // Get all existing widget ids.
869 final AppWidgetHost host = newLauncherWidgetHost();
870 final int[] allWidgets;
871 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700872 // Although the method was defined in O, it has existed since the beginning of time,
873 // so it might work on older platforms as well.
874 allWidgets = host.getAppWidgetIds();
875 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700876 Log.e(TAG, "getAppWidgetIds not supported", e);
877 return;
878 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700879 final HashSet<Integer> validWidgets = new HashSet<>();
880 try (Cursor c = db.query(Favorites.TABLE_NAME,
881 new String[] {Favorites.APPWIDGET_ID },
882 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700883 while (c.moveToNext()) {
884 validWidgets.add(c.getInt(0));
885 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700886 } catch (SQLException ex) {
887 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700888 return;
889 }
890 for (int widgetId : allWidgets) {
891 if (!validWidgets.contains(widgetId)) {
892 try {
893 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
894 host.deleteAppWidgetId(widgetId);
895 } catch (RuntimeException e) {
896 // Ignore
897 }
898 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700899 }
900 }
901
902 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700903 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
904 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
905 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700906 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700907 try (SQLiteTransaction t = new SQLiteTransaction(db);
908 // Only consider the primary user as other users can't have a shortcut.
909 Cursor c = db.query(Favorites.TABLE_NAME,
910 new String[] { Favorites._ID, Favorites.INTENT},
911 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
912 " AND profileId=" + getDefaultUserSerial(),
913 null, null, null, null);
914 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
915 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
916 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700917 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
918 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
919
920 while (c.moveToNext()) {
921 String intentDescription = c.getString(intentIndex);
922 Intent intent;
923 try {
924 intent = Intent.parseUri(intentDescription, 0);
925 } catch (URISyntaxException e) {
926 Log.e(TAG, "Unable to parse intent", e);
927 continue;
928 }
929
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700930 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700931 continue;
932 }
933
934 long id = c.getLong(idIndex);
935 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700936 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700937 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700938 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700939 } catch (SQLException ex) {
940 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700941 }
942 }
943
944 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800945 * Recreates workspace table and migrates data to the new table.
946 */
947 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700948 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
949 final ArrayList<Long> sortedIDs;
950
951 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800952 new String[] {LauncherSettings.WorkspaceScreens._ID},
953 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700954 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
955 // Use LinkedHashSet so that ordering is preserved
956 sortedIDs = new ArrayList<>(
957 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800958 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700959 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700960 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800961
962 // Add all screen ids back
963 int total = sortedIDs.size();
964 for (int i = 0; i < total; i++) {
965 ContentValues values = new ContentValues();
966 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
967 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
968 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700969 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800970 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700971 t.commit();
972 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800973 } catch (SQLException ex) {
974 // Old version remains, which means we wipe old data
975 Log.e(TAG, ex.getMessage(), ex);
976 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800977 }
978 return true;
979 }
980
Adam Cohen091440a2015-03-18 14:16:05 -0700981 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700982 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800983 if (addRankColumn) {
984 // Insert new column for holding rank
985 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
986 }
987
988 // Get a map for folder ID to folder width
989 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
990 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
991 + " GROUP BY container;",
992 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
993
994 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800995 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
996 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800997 new Object[] {c.getLong(1) + 1, c.getLong(0)});
998 }
999
1000 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001001 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001002 } catch (SQLException ex) {
1003 // Old version remains, which means we wipe old data
1004 Log.e(TAG, ex.getMessage(), ex);
1005 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001006 }
1007 return true;
1008 }
1009
Kenny Guyed131872014-04-30 03:02:21 +01001010 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001011 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -07001012 }
1013
1014 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001015 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001016 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1017 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001018 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001019 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001020 Log.e(TAG, ex.getMessage(), ex);
1021 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001022 }
1023 return true;
1024 }
1025
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001026 // Generates a new ID to use for an object in your database. This method should be only
1027 // called from the main UI thread. As an exception, we do call it when we call the
1028 // constructor from the worker thread; however, this doesn't extend until after the
1029 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1030 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001031 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001032 public long generateNewItemId() {
1033 if (mMaxItemId < 0) {
1034 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001035 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001036 mMaxItemId += 1;
1037 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001038 }
1039
Sunny Goyal55fddc82017-04-06 15:02:52 -07001040 public AppWidgetHost newLauncherWidgetHost() {
1041 return new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID);
1042 }
1043
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001044 @Override
1045 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001046 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001047 }
1048
Chris Wren5dee7af2013-12-20 17:22:11 -05001049 public void checkId(String table, ContentValues values) {
1050 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001051 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001052 mMaxScreenId = Math.max(id, mMaxScreenId);
1053 } else {
1054 mMaxItemId = Math.max(id, mMaxItemId);
1055 }
1056 }
1057
Adam Cohendcd297f2013-06-18 13:13:40 -07001058 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001059 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001060 }
1061
1062 // Generates a new ID to use for an workspace screen in your database. This method
1063 // should be only called from the main UI thread. As an exception, we do call it when we
1064 // call the constructor from the worker thread; however, this doesn't extend until after the
1065 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1066 // after that point
1067 public long generateNewScreenId() {
1068 if (mMaxScreenId < 0) {
1069 throw new RuntimeException("Error: max screen id was not initialized");
1070 }
1071 mMaxScreenId += 1;
1072 return mMaxScreenId;
1073 }
1074
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001076 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001077 }
1078
Adam Cohen091440a2015-03-18 14:16:05 -07001079 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001080 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001081 // TODO: Use multiple loaders with fall-back and transaction.
1082 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001083
1084 // Add the screens specified by the items above
1085 Collections.sort(screenIds);
1086 int rank = 0;
1087 ContentValues values = new ContentValues();
1088 for (Long id : screenIds) {
1089 values.clear();
1090 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1091 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001092 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001093 throw new RuntimeException("Failed initialize screen table"
1094 + "from default layout");
1095 }
1096 rank++;
1097 }
1098
1099 // Ensure that the max ids are initialized
1100 mMaxItemId = initializeMaxItemId(db);
1101 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001102
Adam Cohen71483f42014-05-15 14:04:01 -07001103 return count;
1104 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001105 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001106
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001107 /**
1108 * @return the max _id in the provided table.
1109 */
Adam Cohen091440a2015-03-18 14:16:05 -07001110 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001111 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1112 // get the result
1113 long id = -1;
1114 if (c != null && c.moveToNext()) {
1115 id = c.getLong(0);
1116 }
1117 if (c != null) {
1118 c.close();
1119 }
1120
1121 if (id == -1) {
1122 throw new RuntimeException("Error: could not query max id in " + table);
1123 }
1124
1125 return id;
1126 }
1127
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001128 static class SqlArguments {
1129 public final String table;
1130 public final String where;
1131 public final String[] args;
1132
1133 SqlArguments(Uri url, String where, String[] args) {
1134 if (url.getPathSegments().size() == 1) {
1135 this.table = url.getPathSegments().get(0);
1136 this.where = where;
1137 this.args = args;
1138 } else if (url.getPathSegments().size() != 2) {
1139 throw new IllegalArgumentException("Invalid URI: " + url);
1140 } else if (!TextUtils.isEmpty(where)) {
1141 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1142 } else {
1143 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001144 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001145 this.args = null;
1146 }
1147 }
1148
1149 SqlArguments(Uri url) {
1150 if (url.getPathSegments().size() == 1) {
1151 table = url.getPathSegments().get(0);
1152 where = null;
1153 args = null;
1154 } else {
1155 throw new IllegalArgumentException("Invalid URI: " + url);
1156 }
1157 }
1158 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001159
1160 private static class ChangeListenerWrapper implements Handler.Callback {
1161
1162 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1163 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1164 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1165
1166 private LauncherProviderChangeListener mListener;
1167
1168 @Override
1169 public boolean handleMessage(Message msg) {
1170 if (mListener != null) {
1171 switch (msg.what) {
1172 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001173 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001174 break;
1175 case MSG_EXTRACTED_COLORS_CHANGED:
1176 mListener.onExtractedColorsChanged();
1177 break;
1178 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001179 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001180 break;
1181 }
1182 }
1183 return true;
1184 }
1185 }
Adam Cohen72960972014-01-15 18:13:55 -08001186}