blob: c84a4312df1972d345cd63097f0b045b43fd8fce [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 Goyal05f30882017-05-03 12:42:18 -070059import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070061import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070062import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070063import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070064import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070065import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070066import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070067
Sunny Goyal05f30882017-05-03 12:42:18 -070068import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Sunny Goyal55fddc82017-04-06 15:02:52 -070071import java.lang.reflect.Method;
Mike Cleronb87bd162009-10-30 16:36:56 -070072import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070073import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070074import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070075import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070076import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070079 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080080 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
Sunny Goyal05f30882017-05-03 12:42:18 -070082 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
83
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070084 /**
85 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
86 */
Sunny Goyal05f30882017-05-03 12:42:18 -070087 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Sunny Goyal3d706ad2017-03-06 16:56:39 -080089 public static final String AUTHORITY = (BuildConfig.APPLICATION_ID + ".settings").intern();
Winson Chung3d503fb2011-07-13 17:25:49 -070090
Sunny Goyale87e6ab2014-11-21 22:42:53 -080091 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070093 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
94
Sunny Goyalb5b55c82016-05-10 12:28:59 -070095 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
96 private Handler mListenerHandler;
97
Sunny Goyalf076eae2016-01-11 12:25:10 -080098 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800100 /**
101 * $ adb shell dumpsys activity provider com.android.launcher3
102 */
103 @Override
104 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
105 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
106 if (appState == null || !appState.getModel().isModelLoaded()) {
107 return;
108 }
109 appState.getModel().dumpState("", fd, writer, args);
110 }
111
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112 @Override
113 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800114 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700115 Log.d(TAG, "Launcher process started");
116 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700117 mListenerHandler = new Handler(mListenerWrapper);
118
Sunny Goyalfdbef272017-02-01 12:52:54 -0800119 // The content provider exists for the entire duration of the launcher main process and
120 // is the first component to get created. Initializing FileLog here ensures that it's
121 // always available in the main process.
122 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700123 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700124 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 return true;
126 }
127
Sunny Goyald3849d12015-10-29 10:28:32 -0700128 /**
129 * Sets a provider listener.
130 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700131 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700132 Preconditions.assertUIThread();
133 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700134 }
135
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136 @Override
137 public String getType(Uri uri) {
138 SqlArguments args = new SqlArguments(uri, null, null);
139 if (TextUtils.isEmpty(args.where)) {
140 return "vnd.android.cursor.dir/" + args.table;
141 } else {
142 return "vnd.android.cursor.item/" + args.table;
143 }
144 }
145
Sunny Goyalf076eae2016-01-11 12:25:10 -0800146 /**
147 * Overridden in tests
148 */
149 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700150 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700151 if (LauncherAppState.PROFILE_STARTUP) {
152 Trace.beginSection("Opening workspace DB");
153 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700154 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700155
156 if (RestoreDbTask.isPending(getContext())) {
157 if (!RestoreDbTask.performRestore(mOpenHelper)) {
158 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
159 }
160 // Set is pending to false irrespective of the result, so that it doesn't get
161 // executed again.
162 RestoreDbTask.setPending(getContext(), false);
163 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700164
165 if (LauncherAppState.PROFILE_STARTUP) {
166 Trace.endSection();
167 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700168 }
169 }
170
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171 @Override
172 public Cursor query(Uri uri, String[] projection, String selection,
173 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700174 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175
176 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
177 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
178 qb.setTables(args.table);
179
Romain Guy73b979d2009-06-09 12:57:21 -0700180 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
182 result.setNotificationUri(getContext().getContentResolver(), uri);
183
184 return result;
185 }
186
Adam Cohen091440a2015-03-18 14:16:05 -0700187 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700188 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500189 if (values == null) {
190 throw new RuntimeException("Error: attempting to insert null values");
191 }
Adam Cohen71483f42014-05-15 14:04:01 -0700192 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700193 throw new RuntimeException("Error: attempting to add item without specifying an id");
194 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500195 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700196 return db.insert(table, nullColumnHack, values);
197 }
198
Sunny Goyald1064182015-08-13 12:08:30 -0700199 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700200 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700201 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
202 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800203 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700204 }
205 }
206 }
207
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208 @Override
209 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700210 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 SqlArguments args = new SqlArguments(uri);
212
Sunny Goyald1064182015-08-13 12:08:30 -0700213 // In very limited cases, we support system|signature permission apps to modify the db.
214 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700215 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700216 return null;
217 }
218 }
219
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400221 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700222 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800223 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224
225 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700226 notifyListeners();
227
Sunny Goyalc74e4192015-09-08 14:01:03 -0700228 if (Utilities.ATLEAST_MARSHMALLOW) {
229 reloadLauncherIfExternal();
230 } else {
231 // Deprecated behavior to support legacy devices which rely on provider callbacks.
232 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
233 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800234 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700235 }
236
237 String notify = uri.getQueryParameter("notify");
238 if (notify == null || "true".equals(notify)) {
239 getContext().getContentResolver().notifyChange(uri, null);
240 }
241 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return uri;
243 }
244
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700245 private boolean initializeExternalAdd(ContentValues values) {
246 // 1. Ensure that externally added items have a valid item id
247 long id = mOpenHelper.generateNewItemId();
248 values.put(LauncherSettings.Favorites._ID, id);
249
250 // 2. In the case of an app widget, and if no app widget id is specified, we
251 // attempt allocate and bind the widget.
252 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
253 if (itemType != null &&
254 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
255 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
256
257 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
258 ComponentName cn = ComponentName.unflattenFromString(
259 values.getAsString(Favorites.APPWIDGET_PROVIDER));
260
261 if (cn != null) {
262 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700263 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
264 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700265 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
266 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700267 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700268 return false;
269 }
270 } catch (RuntimeException e) {
271 Log.e(TAG, "Failed to initialize external widget", e);
272 return false;
273 }
274 } else {
275 return false;
276 }
277 }
278
279 // Add screen id if not present
280 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
281 SQLiteStatement stmp = null;
282 try {
283 stmp = mOpenHelper.getWritableDatabase().compileStatement(
284 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
285 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
286 stmp.bindLong(1, screenId);
287
288 ContentValues valuesInserted = new ContentValues();
289 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
290 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
291 return true;
292 } catch (Exception e) {
293 return false;
294 } finally {
295 Utilities.closeSilently(stmp);
296 }
297 }
298
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 @Override
300 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700301 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 SqlArguments args = new SqlArguments(uri);
303
304 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700305 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 int numValues = values.length;
307 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400308 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700309 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
310 return 0;
311 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800312 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700313 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800314 }
315
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700316 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700317 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318 return values.length;
319 }
320
321 @Override
Yura085c8532014-02-11 15:15:29 +0000322 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
323 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700324 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700325 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000326 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700327 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700328 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000329 return result;
Yura085c8532014-02-11 15:15:29 +0000330 }
331 }
332
333 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700335 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
337
338 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339
Louis Begina9c21c62016-08-15 15:18:41 -0700340 if (Binder.getCallingPid() != Process.myPid()
341 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700342 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700343 }
344 int count = db.delete(args.table, args.where, args.args);
345 if (count > 0) {
346 notifyListeners();
347 reloadLauncherIfExternal();
348 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 return count;
350 }
351
352 @Override
353 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700354 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
356
Chris Wren1ada10d2013-09-13 18:01:38 -0400357 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800358 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
359 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700360 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800361
Sunny Goyald1064182015-08-13 12:08:30 -0700362 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800363 return count;
364 }
365
Sunny Goyal7779d622015-06-11 16:18:39 -0700366 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700367 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700368 if (Binder.getCallingUid() != Process.myUid()) {
369 return null;
370 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700371 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700372
373 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700374 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
375 String extractedColors = extras.getString(
376 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
377 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
378 Utilities.getPrefs(getContext()).edit()
379 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
380 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
381 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700382 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700383 Bundle result = new Bundle();
384 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
385 return result;
386 }
Sunny Goyald2497482015-09-22 18:24:19 -0700387 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
388 clearFlagEmptyDbCreated();
389 return null;
390 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700391 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
392 Bundle result = new Bundle();
393 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
394 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
395 return result;
396 }
Sunny Goyald2497482015-09-22 18:24:19 -0700397 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
398 Bundle result = new Bundle();
399 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
400 return result;
401 }
402 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
403 Bundle result = new Bundle();
404 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
405 return result;
406 }
407 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
408 Bundle result = new Bundle();
409 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
410 return result;
411 }
412 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800413 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700414 return null;
415 }
416 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
417 loadDefaultFavoritesIfNecessary();
418 return null;
419 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700420 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
421 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
422 return null;
423 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700424 }
425 return null;
426 }
427
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 /**
429 * Deletes any empty folder from the DB.
430 * @return Ids of deleted folders.
431 */
Sunny Goyald2497482015-09-22 18:24:19 -0700432 private ArrayList<Long> deleteEmptyFolders() {
433 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700434 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700435 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700436 // Select folders whose id do not match any container value.
437 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
438 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
439 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
440 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700441 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700442 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700443 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700444 selection, null, null, null, null)) {
445 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700446 }
Sunny Goyald2497482015-09-22 18:24:19 -0700447 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700448 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700449 LauncherSettings.Favorites._ID, folderIds), null);
450 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700451 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700452 } catch (SQLException ex) {
453 Log.e(TAG, ex.getMessage(), ex);
454 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700455 }
456 return folderIds;
457 }
458
Sunny Goyalf076eae2016-01-11 12:25:10 -0800459 /**
460 * Overridden in tests
461 */
462 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700463 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400464 }
465
Adam Cohen091440a2015-03-18 14:16:05 -0700466 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400467 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 }
469
Sunny Goyald2497482015-09-22 18:24:19 -0700470 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700471 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700472 }
473
Sunny Goyal42de82f2014-09-26 22:09:29 -0700474 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700475 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700476 * 1) From the app restrictions
477 * 2) From a package provided by play store
478 * 3) From a partner configuration APK, already in the system image
479 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700480 */
Sunny Goyald2497482015-09-22 18:24:19 -0700481 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700482 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700483
Winson Chungc763c4e2013-07-19 13:49:06 -0700484 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500485 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200486
Sunny Goyal55fddc82017-04-06 15:02:52 -0700487 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700489 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700490 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700491 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700492 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700493 final Partner partner = Partner.get(getContext().getPackageManager());
494 if (partner != null && partner.hasDefaultLayout()) {
495 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700496 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700497 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700498 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700499 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700500 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700501 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700502 }
503 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700504
Sunny Goyal9d219682014-10-23 14:21:02 -0700505 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700506 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700507 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700508 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800509
510 // There might be some partially restored DB items, due to buggy restore logic in
511 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800512 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700513 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700514 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
515 && usingExternallyProvidedLayout) {
516 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800517 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700518 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700520 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700521 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700522 }
523 }
524
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700525 /**
526 * Creates workspace loader from an XML resource listed in the app restrictions.
527 *
528 * @return the loader if the restrictions are set and the resource exists; null otherwise.
529 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700530 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700531 Context ctx = getContext();
532 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
533 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700534 if (bundle == null) {
535 return null;
536 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700537
Sunny Goyal35ca8732015-04-06 10:45:31 -0700538 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700539 if (packageName != null) {
540 try {
541 Resources targetResources = ctx.getPackageManager()
542 .getResourcesForApplication(packageName);
543 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700544 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700545 } catch (NameNotFoundException e) {
546 Log.e(TAG, "Target package for restricted profile not found", e);
547 return null;
548 }
549 }
550 return null;
551 }
552
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700553 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800554 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700555 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700556 mOpenHelper, getContext().getResources(), defaultLayout);
557 }
558
Sunny Goyald3849d12015-10-29 10:28:32 -0700559 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800560 * The class is subclassed in tests to create an in-memory db.
561 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700562 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700563 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800564 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700565 private long mMaxItemId = -1;
566 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800567
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
569 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700570 // Table creation sometimes fails silently, which leads to a crash loop.
571 // This way, we will try to create a table every time after crash, so the device
572 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700573 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700574 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
575 // This operation is a no-op if the table already exists.
576 addFavoritesTable(getWritableDatabase(), true);
577 addWorkspacesTable(getWritableDatabase(), true);
578 }
579
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700580 initIds();
581 }
582
583 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700584 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700585 */
586 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700587 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700588 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700589 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700590 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700591 }
592
593 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700594 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
595 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700596 if (mMaxItemId == -1) {
597 mMaxItemId = initializeMaxItemId(getWritableDatabase());
598 }
599 if (mMaxScreenId == -1) {
600 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700601 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 }
603
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700604 private boolean tableExists(String tableName) {
605 Cursor c = getReadableDatabase().query(
606 true, "sqlite_master", new String[] {"tbl_name"},
607 "tbl_name = ?", new String[] {tableName},
608 null, null, null, null, null);
609 try {
610 return c.getCount() > 0;
611 } finally {
612 c.close();
613 }
614 }
615
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 @Override
617 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800618 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700619
Adam Cohendcd297f2013-06-18 13:13:40 -0700620 mMaxItemId = 1;
621 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700622
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700623 addFavoritesTable(db, false);
624 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800626 // Fresh and clean launcher DB.
627 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800628 onEmptyDbCreated();
629 }
630
631 /**
632 * Overriden in tests.
633 */
634 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700635 // Database was just created, so wipe any previous widgets
636 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700637 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700638 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530639 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700640 }
641
Sunny Goyalf076eae2016-01-11 12:25:10 -0800642 // Set the flag for empty DB
643 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700644
645 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800646 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800647 mContext);
648 }
649
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700650 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800651 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800652 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653 }
654
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700655 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700656 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700657 }
658
659 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
660 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700661 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800662 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400663 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
664 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700665 ");");
666 }
667
Adam Cohen119285e2014-04-02 16:59:08 -0700668 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700669 // Delete items directly on the workspace who's screen id doesn't exist
670 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
671 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700672 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700674 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700675 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700676 " AND " +
677 LauncherSettings.Favorites.CONTAINER + " = " +
678 LauncherSettings.Favorites.CONTAINER_DESKTOP;
679 db.execSQL(removeOrphanedDesktopItems);
680
681 // Delete items contained in folders which no longer exist (after above statement)
682 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
683 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700684 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700685 " WHERE " +
686 LauncherSettings.Favorites.CONTAINER + " <> " +
687 LauncherSettings.Favorites.CONTAINER_DESKTOP +
688 " AND "
689 + LauncherSettings.Favorites.CONTAINER + " <> " +
690 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
691 " AND "
692 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700693 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700694 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
695 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
696 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700697 }
698
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700700 public void onOpen(SQLiteDatabase db) {
701 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700702
703 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
704 if (!schemaFile.exists()) {
705 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700706 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700707 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
708 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700709 }
710
711 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700712 * One-time data updated before support of onDowngrade was added. This update is backwards
713 * compatible and can safely be run multiple times.
714 * Note: No new logic should be added here after release, as the new logic might not get
715 * executed on an existing device.
716 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700717 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700718 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
719 // Remove "profile extra"
720 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
721 for (UserHandle user : um.getUserProfiles()) {
722 long serial = um.getSerialNumberForUser(user);
723 String sql = "update favorites set intent = replace(intent, "
724 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
725 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700726 }
727 }
728
729 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800730 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700731 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 switch (oldVersion) {
733 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800734 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 case 12: {
736 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
737 // to persist workspace screens and their relative order.
738 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700739 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800740 }
741 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700742 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 // Insert new column for holding widget provider name
744 db.execSQL("ALTER TABLE favorites " +
745 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700746 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800747 } catch (SQLException ex) {
748 Log.e(TAG, ex.getMessage(), ex);
749 // Old version remains, which means we wipe old data
750 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 }
752 }
753 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700754 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 // Insert new column for holding update timestamp
756 db.execSQL("ALTER TABLE favorites " +
757 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
758 db.execSQL("ALTER TABLE workspaceScreens " +
759 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700760 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 } catch (SQLException ex) {
762 Log.e(TAG, ex.getMessage(), ex);
763 // Old version remains, which means we wipe old data
764 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800765 }
766 }
767 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700768 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800769 // Old version remains, which means we wipe old data
770 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800771 }
772 }
773 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700774 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800775 }
776 case 17: {
777 // No-op
778 }
779 case 18: {
780 // Due to a data loss bug, some users may have items associated with screen ids
781 // which no longer exist. Since this can cause other problems, and since the user
782 // will never see these items anyway, we use database upgrade as an opportunity to
783 // clean things up.
784 removeOrphanedItems(db);
785 }
786 case 19: {
787 // Add userId column
788 if (!addProfileColumn(db)) {
789 // Old version remains, which means we wipe old data
790 break;
791 }
792 }
793 case 20:
794 if (!updateFolderItemsRank(db, true)) {
795 break;
796 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800797 case 21:
798 // Recreate workspace table with screen id a primary key
799 if (!recreateWorkspaceTable(db)) {
800 break;
801 }
802 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700803 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
804 // Old version remains, which means we wipe old data
805 break;
806 }
807 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700808 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700809 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700810 case 24:
811 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700812 case 25:
813 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700814 case 26:
815 // QSB was moved to the grid. Clear the first row on screen 0.
816 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800817 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700818 break;
819 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700820 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800821 // DB Upgraded successfully
822 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400823 }
824
Sunny Goyala2cc6242015-01-14 14:23:02 -0800825 // DB was not upgraded
826 Log.w(TAG, "Destroying all old data.");
827 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800828 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800829
Adam Cohen9b1d0622014-05-21 19:01:57 -0700830 @Override
831 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700832 try {
833 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
834 .onDowngrade(db, oldVersion, newVersion);
835 } catch (Exception e) {
836 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
837 ". Wiping databse.", e);
838 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700839 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700840 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700841
Sunny Goyal42de82f2014-09-26 22:09:29 -0700842 /**
843 * Clears all the data for a fresh start.
844 */
845 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700846 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800847 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
848 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
849 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700850 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800851 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700852 }
853
Sunny Goyald2f38192015-02-25 10:46:34 -0800854 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700855 * Removes widgets which are registered to the Launcher's host, but are not present
856 * in our model.
857 */
858 public void removeGhostWidgets(SQLiteDatabase db) {
859 // Get all existing widget ids.
860 final AppWidgetHost host = newLauncherWidgetHost();
861 final int[] allWidgets;
862 try {
863 Method getter = AppWidgetHost.class.getDeclaredMethod("getAppWidgetIds");
864 getter.setAccessible(true);
865 allWidgets = (int[]) getter.invoke(host);
866 } catch (Exception e) {
867 Log.e(TAG, "getAppWidgetIds not supported", e);
868 return;
869 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700870 final HashSet<Integer> validWidgets = new HashSet<>();
871 try (Cursor c = db.query(Favorites.TABLE_NAME,
872 new String[] {Favorites.APPWIDGET_ID },
873 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700874 while (c.moveToNext()) {
875 validWidgets.add(c.getInt(0));
876 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700877 } catch (SQLException ex) {
878 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700879 return;
880 }
881 for (int widgetId : allWidgets) {
882 if (!validWidgets.contains(widgetId)) {
883 try {
884 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
885 host.deleteAppWidgetId(widgetId);
886 } catch (RuntimeException e) {
887 // Ignore
888 }
889 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700890 }
891 }
892
893 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700894 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
895 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
896 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700897 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700898 try (SQLiteTransaction t = new SQLiteTransaction(db);
899 // Only consider the primary user as other users can't have a shortcut.
900 Cursor c = db.query(Favorites.TABLE_NAME,
901 new String[] { Favorites._ID, Favorites.INTENT},
902 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
903 " AND profileId=" + getDefaultUserSerial(),
904 null, null, null, null);
905 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
906 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
907 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700908 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
909 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
910
911 while (c.moveToNext()) {
912 String intentDescription = c.getString(intentIndex);
913 Intent intent;
914 try {
915 intent = Intent.parseUri(intentDescription, 0);
916 } catch (URISyntaxException e) {
917 Log.e(TAG, "Unable to parse intent", e);
918 continue;
919 }
920
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700921 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700922 continue;
923 }
924
925 long id = c.getLong(idIndex);
926 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700927 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700928 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700929 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700930 } catch (SQLException ex) {
931 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700932 }
933 }
934
935 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800936 * Recreates workspace table and migrates data to the new table.
937 */
938 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700939 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
940 final ArrayList<Long> sortedIDs;
941
942 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800943 new String[] {LauncherSettings.WorkspaceScreens._ID},
944 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700945 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
946 // Use LinkedHashSet so that ordering is preserved
947 sortedIDs = new ArrayList<>(
948 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800949 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700950 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700951 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800952
953 // Add all screen ids back
954 int total = sortedIDs.size();
955 for (int i = 0; i < total; i++) {
956 ContentValues values = new ContentValues();
957 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
958 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
959 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700960 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800961 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700962 t.commit();
963 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800964 } catch (SQLException ex) {
965 // Old version remains, which means we wipe old data
966 Log.e(TAG, ex.getMessage(), ex);
967 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800968 }
969 return true;
970 }
971
Adam Cohen091440a2015-03-18 14:16:05 -0700972 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700973 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800974 if (addRankColumn) {
975 // Insert new column for holding rank
976 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
977 }
978
979 // Get a map for folder ID to folder width
980 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
981 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
982 + " GROUP BY container;",
983 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
984
985 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800986 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
987 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800988 new Object[] {c.getLong(1) + 1, c.getLong(0)});
989 }
990
991 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700992 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800993 } catch (SQLException ex) {
994 // Old version remains, which means we wipe old data
995 Log.e(TAG, ex.getMessage(), ex);
996 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800997 }
998 return true;
999 }
1000
Kenny Guyed131872014-04-30 03:02:21 +01001001 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001002 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -07001003 }
1004
1005 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001006 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001007 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1008 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001009 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001010 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001011 Log.e(TAG, ex.getMessage(), ex);
1012 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001013 }
1014 return true;
1015 }
1016
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 // Generates a new ID to use for an object in your database. This method should be only
1018 // called from the main UI thread. As an exception, we do call it when we call the
1019 // constructor from the worker thread; however, this doesn't extend until after the
1020 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1021 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001022 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001023 public long generateNewItemId() {
1024 if (mMaxItemId < 0) {
1025 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001026 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001027 mMaxItemId += 1;
1028 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001029 }
1030
Sunny Goyal55fddc82017-04-06 15:02:52 -07001031 public AppWidgetHost newLauncherWidgetHost() {
1032 return new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID);
1033 }
1034
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001035 @Override
1036 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001037 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001038 }
1039
Chris Wren5dee7af2013-12-20 17:22:11 -05001040 public void checkId(String table, ContentValues values) {
1041 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001042 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001043 mMaxScreenId = Math.max(id, mMaxScreenId);
1044 } else {
1045 mMaxItemId = Math.max(id, mMaxItemId);
1046 }
1047 }
1048
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001050 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001051 }
1052
1053 // Generates a new ID to use for an workspace screen in your database. This method
1054 // should be only called from the main UI thread. As an exception, we do call it when we
1055 // call the constructor from the worker thread; however, this doesn't extend until after the
1056 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1057 // after that point
1058 public long generateNewScreenId() {
1059 if (mMaxScreenId < 0) {
1060 throw new RuntimeException("Error: max screen id was not initialized");
1061 }
1062 mMaxScreenId += 1;
1063 return mMaxScreenId;
1064 }
1065
Adam Cohendcd297f2013-06-18 13:13:40 -07001066 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001067 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001068 }
1069
Adam Cohen091440a2015-03-18 14:16:05 -07001070 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001071 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001072 // TODO: Use multiple loaders with fall-back and transaction.
1073 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001074
1075 // Add the screens specified by the items above
1076 Collections.sort(screenIds);
1077 int rank = 0;
1078 ContentValues values = new ContentValues();
1079 for (Long id : screenIds) {
1080 values.clear();
1081 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1082 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001083 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001084 throw new RuntimeException("Failed initialize screen table"
1085 + "from default layout");
1086 }
1087 rank++;
1088 }
1089
1090 // Ensure that the max ids are initialized
1091 mMaxItemId = initializeMaxItemId(db);
1092 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001093
Adam Cohen71483f42014-05-15 14:04:01 -07001094 return count;
1095 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001096 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001097
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001098 /**
1099 * @return the max _id in the provided table.
1100 */
Adam Cohen091440a2015-03-18 14:16:05 -07001101 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001102 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1103 // get the result
1104 long id = -1;
1105 if (c != null && c.moveToNext()) {
1106 id = c.getLong(0);
1107 }
1108 if (c != null) {
1109 c.close();
1110 }
1111
1112 if (id == -1) {
1113 throw new RuntimeException("Error: could not query max id in " + table);
1114 }
1115
1116 return id;
1117 }
1118
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001119 static class SqlArguments {
1120 public final String table;
1121 public final String where;
1122 public final String[] args;
1123
1124 SqlArguments(Uri url, String where, String[] args) {
1125 if (url.getPathSegments().size() == 1) {
1126 this.table = url.getPathSegments().get(0);
1127 this.where = where;
1128 this.args = args;
1129 } else if (url.getPathSegments().size() != 2) {
1130 throw new IllegalArgumentException("Invalid URI: " + url);
1131 } else if (!TextUtils.isEmpty(where)) {
1132 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1133 } else {
1134 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001135 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 this.args = null;
1137 }
1138 }
1139
1140 SqlArguments(Uri url) {
1141 if (url.getPathSegments().size() == 1) {
1142 table = url.getPathSegments().get(0);
1143 where = null;
1144 args = null;
1145 } else {
1146 throw new IllegalArgumentException("Invalid URI: " + url);
1147 }
1148 }
1149 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001150
1151 private static class ChangeListenerWrapper implements Handler.Callback {
1152
1153 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1154 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1155 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1156
1157 private LauncherProviderChangeListener mListener;
1158
1159 @Override
1160 public boolean handleMessage(Message msg) {
1161 if (mListener != null) {
1162 switch (msg.what) {
1163 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001164 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001165 break;
1166 case MSG_EXTRACTED_COLORS_CHANGED:
1167 mListener.onExtractedColorsChanged();
1168 break;
1169 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001170 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001171 break;
1172 }
1173 }
1174 return true;
1175 }
1176 }
Adam Cohen72960972014-01-15 18:13:55 -08001177}