blob: 8f56eb69e4767e8ed7ffeab1534f28b574ac7ced [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;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070057import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070058import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070059import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070060import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070061import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070062import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070063import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070064
Mike Cleronb87bd162009-10-30 16:36:56 -070065import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070066import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070067import java.util.Collections;
Louis Begina9c21c62016-08-15 15:18:41 -070068import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070071 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080072 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070074 private static final int DATABASE_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Sunny Goyale5bb7052015-07-27 14:36:07 -070076 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070077
Sunny Goyale87e6ab2014-11-21 22:42:53 -080078 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070080 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
81
Sunny Goyalb5b55c82016-05-10 12:28:59 -070082 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
83 private Handler mListenerHandler;
84
Sunny Goyalf076eae2016-01-11 12:25:10 -080085 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
87 @Override
88 public boolean onCreate() {
Sunny Goyale26d1002016-06-20 14:52:14 -070089 if (ProviderConfig.IS_DOGFOOD_BUILD) {
90 Log.d(TAG, "Launcher process started");
91 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -070092 mListenerHandler = new Handler(mListenerWrapper);
93
Daniel Sandlere4f98912013-06-25 15:13:26 -040094 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095 return true;
96 }
97
Sunny Goyald3849d12015-10-29 10:28:32 -070098 /**
99 * Sets a provider listener.
100 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700102 Preconditions.assertUIThread();
103 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700104 }
105
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106 @Override
107 public String getType(Uri uri) {
108 SqlArguments args = new SqlArguments(uri, null, null);
109 if (TextUtils.isEmpty(args.where)) {
110 return "vnd.android.cursor.dir/" + args.table;
111 } else {
112 return "vnd.android.cursor.item/" + args.table;
113 }
114 }
115
Sunny Goyalf076eae2016-01-11 12:25:10 -0800116 /**
117 * Overridden in tests
118 */
119 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700120 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700121 if (LauncherAppState.PROFILE_STARTUP) {
122 Trace.beginSection("Opening workspace DB");
123 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700124 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700125
126 if (RestoreDbTask.isPending(getContext())) {
127 if (!RestoreDbTask.performRestore(mOpenHelper)) {
128 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
129 }
130 // Set is pending to false irrespective of the result, so that it doesn't get
131 // executed again.
132 RestoreDbTask.setPending(getContext(), false);
133 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700134
135 if (LauncherAppState.PROFILE_STARTUP) {
136 Trace.endSection();
137 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700138 }
139 }
140
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141 @Override
142 public Cursor query(Uri uri, String[] projection, String selection,
143 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700144 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145
146 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
147 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
148 qb.setTables(args.table);
149
Romain Guy73b979d2009-06-09 12:57:21 -0700150 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800151 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
152 result.setNotificationUri(getContext().getContentResolver(), uri);
153
154 return result;
155 }
156
Adam Cohen091440a2015-03-18 14:16:05 -0700157 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500159 if (values == null) {
160 throw new RuntimeException("Error: attempting to insert null values");
161 }
Adam Cohen71483f42014-05-15 14:04:01 -0700162 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700163 throw new RuntimeException("Error: attempting to add item without specifying an id");
164 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500165 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700166 return db.insert(table, nullColumnHack, values);
167 }
168
Sunny Goyald1064182015-08-13 12:08:30 -0700169 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700170 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700171 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
172 if (app != null) {
173 app.reloadWorkspace();
174 }
175 }
176 }
177
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178 @Override
179 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700180 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 SqlArguments args = new SqlArguments(uri);
182
Sunny Goyald1064182015-08-13 12:08:30 -0700183 // In very limited cases, we support system|signature permission apps to modify the db.
184 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700185 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700186 return null;
187 }
188 }
189
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400191 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700192 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800193 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194
195 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700196 notifyListeners();
197
Sunny Goyalc74e4192015-09-08 14:01:03 -0700198 if (Utilities.ATLEAST_MARSHMALLOW) {
199 reloadLauncherIfExternal();
200 } else {
201 // Deprecated behavior to support legacy devices which rely on provider callbacks.
202 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
203 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
204 app.reloadWorkspace();
205 }
206
207 String notify = uri.getQueryParameter("notify");
208 if (notify == null || "true".equals(notify)) {
209 getContext().getContentResolver().notifyChange(uri, null);
210 }
211 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 return uri;
213 }
214
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700215 private boolean initializeExternalAdd(ContentValues values) {
216 // 1. Ensure that externally added items have a valid item id
217 long id = mOpenHelper.generateNewItemId();
218 values.put(LauncherSettings.Favorites._ID, id);
219
220 // 2. In the case of an app widget, and if no app widget id is specified, we
221 // attempt allocate and bind the widget.
222 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
223 if (itemType != null &&
224 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
225 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
226
227 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
228 ComponentName cn = ComponentName.unflattenFromString(
229 values.getAsString(Favorites.APPWIDGET_PROVIDER));
230
231 if (cn != null) {
232 try {
233 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
234 .allocateAppWidgetId();
235 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
236 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
237 return false;
238 }
239 } catch (RuntimeException e) {
240 Log.e(TAG, "Failed to initialize external widget", e);
241 return false;
242 }
243 } else {
244 return false;
245 }
246 }
247
248 // Add screen id if not present
249 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
250 SQLiteStatement stmp = null;
251 try {
252 stmp = mOpenHelper.getWritableDatabase().compileStatement(
253 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
254 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
255 stmp.bindLong(1, screenId);
256
257 ContentValues valuesInserted = new ContentValues();
258 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
259 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
260 return true;
261 } catch (Exception e) {
262 return false;
263 } finally {
264 Utilities.closeSilently(stmp);
265 }
266 }
267
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800268 @Override
269 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700270 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800271 SqlArguments args = new SqlArguments(uri);
272
273 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
274 db.beginTransaction();
275 try {
276 int numValues = values.length;
277 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400278 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700279 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
280 return 0;
281 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800282 }
283 db.setTransactionSuccessful();
284 } finally {
285 db.endTransaction();
286 }
287
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700288 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700289 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 return values.length;
291 }
292
293 @Override
Yura085c8532014-02-11 15:15:29 +0000294 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
295 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700296 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000297 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
298 db.beginTransaction();
299 try {
300 ContentProviderResult[] result = super.applyBatch(operations);
301 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700302 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000303 return result;
304 } finally {
305 db.endTransaction();
306 }
307 }
308
309 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700311 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800312 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
313
314 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315
Louis Begina9c21c62016-08-15 15:18:41 -0700316 if (Binder.getCallingPid() != Process.myPid()
317 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
318 String widgetSelection = TextUtils.isEmpty(args.where) ? "1=1" : args.where;
319 widgetSelection = String.format(Locale.ENGLISH, "%1$s = %2$d AND ( %3$s )",
320 Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET, widgetSelection);
321 try (Cursor c = db.query(Favorites.TABLE_NAME, new String[] { Favorites.APPWIDGET_ID },
322 widgetSelection, args.args, null, null, null)) {
323 AppWidgetHost host = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
324 while (c.moveToNext()) {
325 int widgetId = c.getInt(0);
326 if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
327 try {
328 host.deleteAppWidgetId(widgetId);
329 } catch (RuntimeException e) {
330 Log.e(TAG, "Error deleting widget id " + widgetId, e);
331 }
332 }
333 }
334 }
335 }
336 int count = db.delete(args.table, args.where, args.args);
337 if (count > 0) {
338 notifyListeners();
339 reloadLauncherIfExternal();
340 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341 return count;
342 }
343
344 @Override
345 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700346 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
348
Chris Wren1ada10d2013-09-13 18:01:38 -0400349 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
351 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700352 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800353
Sunny Goyald1064182015-08-13 12:08:30 -0700354 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 return count;
356 }
357
Sunny Goyal7779d622015-06-11 16:18:39 -0700358 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700359 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 if (Binder.getCallingUid() != Process.myUid()) {
361 return null;
362 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700363 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700364
365 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700366 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
367 String extractedColors = extras.getString(
368 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
369 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
370 Utilities.getPrefs(getContext()).edit()
371 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
372 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
373 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700374 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700375 Bundle result = new Bundle();
376 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
377 return result;
378 }
Sunny Goyald2497482015-09-22 18:24:19 -0700379 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
380 clearFlagEmptyDbCreated();
381 return null;
382 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700383 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
384 Bundle result = new Bundle();
385 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
386 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
387 return result;
388 }
Sunny Goyald2497482015-09-22 18:24:19 -0700389 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
390 Bundle result = new Bundle();
391 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
392 return result;
393 }
394 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
395 Bundle result = new Bundle();
396 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
397 return result;
398 }
399 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
400 Bundle result = new Bundle();
401 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
402 return result;
403 }
404 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
405 createEmptyDB();
406 return null;
407 }
408 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
409 loadDefaultFavoritesIfNecessary();
410 return null;
411 }
Sunny Goyald2497482015-09-22 18:24:19 -0700412 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800413 // Are you sure? (y/n)
414 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700415 return null;
416 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700417 }
418 return null;
419 }
420
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700421 /**
422 * Deletes any empty folder from the DB.
423 * @return Ids of deleted folders.
424 */
Sunny Goyald2497482015-09-22 18:24:19 -0700425 private ArrayList<Long> deleteEmptyFolders() {
426 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700427 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
428 db.beginTransaction();
429 try {
430 // Select folders whose id do not match any container value.
431 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
432 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
433 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
434 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700435 + Favorites.TABLE_NAME + ")";
436 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700437 new String[] {LauncherSettings.Favorites._ID},
438 selection, null, null, null, null);
439 while (c.moveToNext()) {
440 folderIds.add(c.getLong(0));
441 }
442 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700443 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700444 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700445 LauncherSettings.Favorites._ID, folderIds), null);
446 }
447 db.setTransactionSuccessful();
448 } catch (SQLException ex) {
449 Log.e(TAG, ex.getMessage(), ex);
450 folderIds.clear();
451 } finally {
452 db.endTransaction();
453 }
454 return folderIds;
455 }
456
Sunny Goyalf076eae2016-01-11 12:25:10 -0800457 /**
458 * Overridden in tests
459 */
460 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700461 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400462 }
463
Adam Cohen091440a2015-03-18 14:16:05 -0700464 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400465 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800466 }
467
Brian Muramatsu5524b492012-10-02 16:55:54 -0700468 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700469 * Clears all the data for a fresh start.
470 */
Sunny Goyald2497482015-09-22 18:24:19 -0700471 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700472 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
473 }
474
Sunny Goyald2497482015-09-22 18:24:19 -0700475 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700476 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700477 }
478
Sunny Goyal42de82f2014-09-26 22:09:29 -0700479 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700481 * 1) From the app restrictions
482 * 2) From a package provided by play store
483 * 3) From a partner configuration APK, already in the system image
484 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700485 */
Sunny Goyald2497482015-09-22 18:24:19 -0700486 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700487 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700488
Winson Chungc763c4e2013-07-19 13:49:06 -0700489 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500490 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200491
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700492 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
493 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700494 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700495 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700496 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700497 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700498 final Partner partner = Partner.get(getContext().getPackageManager());
499 if (partner != null && partner.hasDefaultLayout()) {
500 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700501 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700502 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700503 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700504 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700505 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700506 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700507 }
508 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700509
Sunny Goyal9d219682014-10-23 14:21:02 -0700510 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700511 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700512 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700513 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800514
515 // There might be some partially restored DB items, due to buggy restore logic in
516 // previous versions of launcher.
517 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700518 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700519 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
520 && usingExternallyProvidedLayout) {
521 // Unable to load external layout. Cleanup and load the internal layout.
522 createEmptyDB();
523 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700524 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700525 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700526 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700527 }
528 }
529
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700530 /**
531 * Creates workspace loader from an XML resource listed in the app restrictions.
532 *
533 * @return the loader if the restrictions are set and the resource exists; null otherwise.
534 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700535 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700536 Context ctx = getContext();
537 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
538 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700539 if (bundle == null) {
540 return null;
541 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700542
Sunny Goyal35ca8732015-04-06 10:45:31 -0700543 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700544 if (packageName != null) {
545 try {
546 Resources targetResources = ctx.getPackageManager()
547 .getResourcesForApplication(packageName);
548 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700549 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700550 } catch (NameNotFoundException e) {
551 Log.e(TAG, "Target package for restricted profile not found", e);
552 return null;
553 }
554 }
555 return null;
556 }
557
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700558 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700559 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700560 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700561 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700562 mOpenHelper, getContext().getResources(), defaultLayout);
563 }
564
Sunny Goyald3849d12015-10-29 10:28:32 -0700565 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800566 * The class is subclassed in tests to create an in-memory db.
567 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700568 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700569 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800570 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 private long mMaxItemId = -1;
572 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700574 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
575 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700576 // Table creation sometimes fails silently, which leads to a crash loop.
577 // This way, we will try to create a table every time after crash, so the device
578 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700579 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700580 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
581 // This operation is a no-op if the table already exists.
582 addFavoritesTable(getWritableDatabase(), true);
583 addWorkspacesTable(getWritableDatabase(), true);
584 }
585
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700586 initIds();
587 }
588
589 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700590 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700591 */
592 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700593 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700594 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
595 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700596 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700597 }
598
599 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700600 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
601 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700602 if (mMaxItemId == -1) {
603 mMaxItemId = initializeMaxItemId(getWritableDatabase());
604 }
605 if (mMaxScreenId == -1) {
606 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700607 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800608 }
609
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700610 private boolean tableExists(String tableName) {
611 Cursor c = getReadableDatabase().query(
612 true, "sqlite_master", new String[] {"tbl_name"},
613 "tbl_name = ?", new String[] {tableName},
614 null, null, null, null, null);
615 try {
616 return c.getCount() > 0;
617 } finally {
618 c.close();
619 }
620 }
621
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622 @Override
623 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800624 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700625
Adam Cohendcd297f2013-06-18 13:13:40 -0700626 mMaxItemId = 1;
627 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700628
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700629 addFavoritesTable(db, false);
630 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800632 // Fresh and clean launcher DB.
633 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800634 onEmptyDbCreated();
635 }
636
637 /**
638 * Overriden in tests.
639 */
640 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700641 // Database was just created, so wipe any previous widgets
642 if (mWidgetHostResetHandler != null) {
643 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700644 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530645 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700646 }
647
Sunny Goyalf076eae2016-01-11 12:25:10 -0800648 // Set the flag for empty DB
649 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700650
651 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800652 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800653 mContext);
654 }
655
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700656 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800657 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800658 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800659 }
660
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700661 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700662 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700663 }
664
665 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
666 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700667 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800668 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400669 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
670 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700671 ");");
672 }
673
Adam Cohen119285e2014-04-02 16:59:08 -0700674 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700675 // Delete items directly on the workspace who's screen id doesn't exist
676 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
677 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700678 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700679 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700680 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700681 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700682 " AND " +
683 LauncherSettings.Favorites.CONTAINER + " = " +
684 LauncherSettings.Favorites.CONTAINER_DESKTOP;
685 db.execSQL(removeOrphanedDesktopItems);
686
687 // Delete items contained in folders which no longer exist (after above statement)
688 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
689 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700690 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700691 " WHERE " +
692 LauncherSettings.Favorites.CONTAINER + " <> " +
693 LauncherSettings.Favorites.CONTAINER_DESKTOP +
694 " AND "
695 + LauncherSettings.Favorites.CONTAINER + " <> " +
696 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
697 " AND "
698 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700699 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700700 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
701 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
702 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700703 }
704
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800705 @Override
706 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700707 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800708 switch (oldVersion) {
709 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800710 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800711 case 12: {
712 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
713 // to persist workspace screens and their relative order.
714 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700715 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 }
717 case 13: {
718 db.beginTransaction();
719 try {
720 // Insert new column for holding widget provider name
721 db.execSQL("ALTER TABLE favorites " +
722 "ADD COLUMN appWidgetProvider TEXT;");
723 db.setTransactionSuccessful();
724 } catch (SQLException ex) {
725 Log.e(TAG, ex.getMessage(), ex);
726 // Old version remains, which means we wipe old data
727 break;
728 } finally {
729 db.endTransaction();
730 }
731 }
732 case 14: {
733 db.beginTransaction();
734 try {
735 // Insert new column for holding update timestamp
736 db.execSQL("ALTER TABLE favorites " +
737 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
738 db.execSQL("ALTER TABLE workspaceScreens " +
739 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
740 db.setTransactionSuccessful();
741 } catch (SQLException ex) {
742 Log.e(TAG, ex.getMessage(), ex);
743 // Old version remains, which means we wipe old data
744 break;
745 } finally {
746 db.endTransaction();
747 }
748 }
749 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700750 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 // Old version remains, which means we wipe old data
752 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 }
754 }
755 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700756 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 }
758 case 17: {
759 // No-op
760 }
761 case 18: {
762 // Due to a data loss bug, some users may have items associated with screen ids
763 // which no longer exist. Since this can cause other problems, and since the user
764 // will never see these items anyway, we use database upgrade as an opportunity to
765 // clean things up.
766 removeOrphanedItems(db);
767 }
768 case 19: {
769 // Add userId column
770 if (!addProfileColumn(db)) {
771 // Old version remains, which means we wipe old data
772 break;
773 }
774 }
775 case 20:
776 if (!updateFolderItemsRank(db, true)) {
777 break;
778 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800779 case 21:
780 // Recreate workspace table with screen id a primary key
781 if (!recreateWorkspaceTable(db)) {
782 break;
783 }
784 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700785 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
786 // Old version remains, which means we wipe old data
787 break;
788 }
789 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700790 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700791 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700792 case 24:
793 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700794 case 25:
795 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700796 case 26:
797 // QSB was moved to the grid. Clear the first row on screen 0.
798 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800799 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700800 break;
801 }
802 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800803 // DB Upgraded successfully
804 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400805 }
806 }
807
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 // DB was not upgraded
809 Log.w(TAG, "Destroying all old data.");
810 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800811 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800812
Adam Cohen9b1d0622014-05-21 19:01:57 -0700813 @Override
814 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
815 // This shouldn't happen -- throw our hands up in the air and start over.
816 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
817 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700818 createEmptyDB(db);
819 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700820
Sunny Goyal42de82f2014-09-26 22:09:29 -0700821 /**
822 * Clears all the data for a fresh start.
823 */
824 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700825 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
826 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700827 onCreate(db);
828 }
829
Sunny Goyald2f38192015-02-25 10:46:34 -0800830 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700831 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
832 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
833 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700834 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700835 db.beginTransaction();
836 Cursor c = null;
837 SQLiteStatement updateStmt = null;
838
839 try {
840 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700841 long userSerial = getDefaultUserSerial();
842 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 Favorites._ID,
844 Favorites.INTENT,
845 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
846 null, null, null, null);
847
848 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
849 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
850
851 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
852 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
853
854 while (c.moveToNext()) {
855 String intentDescription = c.getString(intentIndex);
856 Intent intent;
857 try {
858 intent = Intent.parseUri(intentDescription, 0);
859 } catch (URISyntaxException e) {
860 Log.e(TAG, "Unable to parse intent", e);
861 continue;
862 }
863
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700864 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700865 continue;
866 }
867
868 long id = c.getLong(idIndex);
869 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700870 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700871 }
872 db.setTransactionSuccessful();
873 } catch (SQLException ex) {
874 Log.w(TAG, "Error deduping shortcuts", ex);
875 } finally {
876 db.endTransaction();
877 if (c != null) {
878 c.close();
879 }
880 if (updateStmt != null) {
881 updateStmt.close();
882 }
883 }
884 }
885
886 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800887 * Recreates workspace table and migrates data to the new table.
888 */
889 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
890 db.beginTransaction();
891 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700892 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800893 new String[] {LauncherSettings.WorkspaceScreens._ID},
894 null, null, null, null,
895 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
896 ArrayList<Long> sortedIDs = new ArrayList<Long>();
897 long maxId = 0;
898 try {
899 while (c.moveToNext()) {
900 Long id = c.getLong(0);
901 if (!sortedIDs.contains(id)) {
902 sortedIDs.add(id);
903 maxId = Math.max(maxId, id);
904 }
905 }
906 } finally {
907 c.close();
908 }
909
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700910 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700911 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800912
913 // Add all screen ids back
914 int total = sortedIDs.size();
915 for (int i = 0; i < total; i++) {
916 ContentValues values = new ContentValues();
917 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
918 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
919 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700920 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800921 }
922 db.setTransactionSuccessful();
923 mMaxScreenId = maxId;
924 } catch (SQLException ex) {
925 // Old version remains, which means we wipe old data
926 Log.e(TAG, ex.getMessage(), ex);
927 return false;
928 } finally {
929 db.endTransaction();
930 }
931 return true;
932 }
933
Adam Cohen091440a2015-03-18 14:16:05 -0700934 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800935 db.beginTransaction();
936 try {
937 if (addRankColumn) {
938 // Insert new column for holding rank
939 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
940 }
941
942 // Get a map for folder ID to folder width
943 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
944 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
945 + " GROUP BY container;",
946 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
947
948 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800949 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
950 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800951 new Object[] {c.getLong(1) + 1, c.getLong(0)});
952 }
953
954 c.close();
955 db.setTransactionSuccessful();
956 } catch (SQLException ex) {
957 // Old version remains, which means we wipe old data
958 Log.e(TAG, ex.getMessage(), ex);
959 return false;
960 } finally {
961 db.endTransaction();
962 }
963 return true;
964 }
965
Kenny Guyed131872014-04-30 03:02:21 +0100966 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700967 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700968 }
969
970 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100971 db.beginTransaction();
972 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700973 db.execSQL("ALTER TABLE favorites ADD COLUMN "
974 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100975 db.setTransactionSuccessful();
976 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100977 Log.e(TAG, ex.getMessage(), ex);
978 return false;
979 } finally {
980 db.endTransaction();
981 }
982 return true;
983 }
984
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700985 // Generates a new ID to use for an object in your database. This method should be only
986 // called from the main UI thread. As an exception, we do call it when we call the
987 // constructor from the worker thread; however, this doesn't extend until after the
988 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
989 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700990 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700991 public long generateNewItemId() {
992 if (mMaxItemId < 0) {
993 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700994 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 mMaxItemId += 1;
996 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700997 }
998
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700999 @Override
1000 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001001 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001002 }
1003
Chris Wren5dee7af2013-12-20 17:22:11 -05001004 public void checkId(String table, ContentValues values) {
1005 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001006 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001007 mMaxScreenId = Math.max(id, mMaxScreenId);
1008 } else {
1009 mMaxItemId = Math.max(id, mMaxItemId);
1010 }
1011 }
1012
Adam Cohendcd297f2013-06-18 13:13:40 -07001013 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001014 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001015 }
1016
1017 // Generates a new ID to use for an workspace screen in your database. This method
1018 // should be only called from the main UI thread. As an exception, we do call it when we
1019 // call the 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
1022 public long generateNewScreenId() {
1023 if (mMaxScreenId < 0) {
1024 throw new RuntimeException("Error: max screen id was not initialized");
1025 }
1026 mMaxScreenId += 1;
1027 return mMaxScreenId;
1028 }
1029
Adam Cohendcd297f2013-06-18 13:13:40 -07001030 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001031 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001032 }
1033
Adam Cohen091440a2015-03-18 14:16:05 -07001034 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001035 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001036 // TODO: Use multiple loaders with fall-back and transaction.
1037 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001038
1039 // Add the screens specified by the items above
1040 Collections.sort(screenIds);
1041 int rank = 0;
1042 ContentValues values = new ContentValues();
1043 for (Long id : screenIds) {
1044 values.clear();
1045 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1046 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001047 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001048 throw new RuntimeException("Failed initialize screen table"
1049 + "from default layout");
1050 }
1051 rank++;
1052 }
1053
1054 // Ensure that the max ids are initialized
1055 mMaxItemId = initializeMaxItemId(db);
1056 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001057
Adam Cohen71483f42014-05-15 14:04:01 -07001058 return count;
1059 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001060 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001061
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001062 /**
1063 * @return the max _id in the provided table.
1064 */
Adam Cohen091440a2015-03-18 14:16:05 -07001065 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001066 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1067 // get the result
1068 long id = -1;
1069 if (c != null && c.moveToNext()) {
1070 id = c.getLong(0);
1071 }
1072 if (c != null) {
1073 c.close();
1074 }
1075
1076 if (id == -1) {
1077 throw new RuntimeException("Error: could not query max id in " + table);
1078 }
1079
1080 return id;
1081 }
1082
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001083 static class SqlArguments {
1084 public final String table;
1085 public final String where;
1086 public final String[] args;
1087
1088 SqlArguments(Uri url, String where, String[] args) {
1089 if (url.getPathSegments().size() == 1) {
1090 this.table = url.getPathSegments().get(0);
1091 this.where = where;
1092 this.args = args;
1093 } else if (url.getPathSegments().size() != 2) {
1094 throw new IllegalArgumentException("Invalid URI: " + url);
1095 } else if (!TextUtils.isEmpty(where)) {
1096 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1097 } else {
1098 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001099 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001100 this.args = null;
1101 }
1102 }
1103
1104 SqlArguments(Uri url) {
1105 if (url.getPathSegments().size() == 1) {
1106 table = url.getPathSegments().get(0);
1107 where = null;
1108 args = null;
1109 } else {
1110 throw new IllegalArgumentException("Invalid URI: " + url);
1111 }
1112 }
1113 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001114
1115 private static class ChangeListenerWrapper implements Handler.Callback {
1116
1117 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1118 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1119 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1120
1121 private LauncherProviderChangeListener mListener;
1122
1123 @Override
1124 public boolean handleMessage(Message msg) {
1125 if (mListener != null) {
1126 switch (msg.what) {
1127 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001128 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001129 break;
1130 case MSG_EXTRACTED_COLORS_CHANGED:
1131 mListener.onExtractedColorsChanged();
1132 break;
1133 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001134 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001135 break;
1136 }
1137 }
1138 return true;
1139 }
1140 }
Adam Cohen72960972014-01-15 18:13:55 -08001141}