blob: b30c3f3cc58c25d78389833ce4c6b56c7dd89f31 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
35import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteOpenHelper;
38import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070042import android.os.Build;
43import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070047import android.os.Trace;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070049import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070054import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.UserHandleCompat;
56import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070057import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040058import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070059import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070063import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Mike Cleronb87bd162009-10-30 16:36:56 -070067import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070068import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070069import java.util.Collections;
Louis Begina9c21c62016-08-15 15:18:41 -070070import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070073 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080074 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070076 private static final int DATABASE_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyale5bb7052015-07-27 14:36:07 -070078 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070079
Sunny Goyale87e6ab2014-11-21 22:42:53 -080080 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070082 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
83
Sunny Goyalb5b55c82016-05-10 12:28:59 -070084 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
85 private Handler mListenerHandler;
86
Sunny Goyalf076eae2016-01-11 12:25:10 -080087 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
89 @Override
90 public boolean onCreate() {
Sunny Goyale26d1002016-06-20 14:52:14 -070091 if (ProviderConfig.IS_DOGFOOD_BUILD) {
92 Log.d(TAG, "Launcher process started");
93 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -070094 mListenerHandler = new Handler(mListenerWrapper);
95
Daniel Sandlere4f98912013-06-25 15:13:26 -040096 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097 return true;
98 }
99
Sunny Goyald3849d12015-10-29 10:28:32 -0700100 /**
101 * Sets a provider listener.
102 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700103 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700104 Preconditions.assertUIThread();
105 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700106 }
107
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108 @Override
109 public String getType(Uri uri) {
110 SqlArguments args = new SqlArguments(uri, null, null);
111 if (TextUtils.isEmpty(args.where)) {
112 return "vnd.android.cursor.dir/" + args.table;
113 } else {
114 return "vnd.android.cursor.item/" + args.table;
115 }
116 }
117
Sunny Goyalf076eae2016-01-11 12:25:10 -0800118 /**
119 * Overridden in tests
120 */
121 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700122 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700123 if (LauncherAppState.PROFILE_STARTUP) {
124 Trace.beginSection("Opening workspace DB");
125 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700126 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700127
128 if (RestoreDbTask.isPending(getContext())) {
129 if (!RestoreDbTask.performRestore(mOpenHelper)) {
130 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
131 }
132 // Set is pending to false irrespective of the result, so that it doesn't get
133 // executed again.
134 RestoreDbTask.setPending(getContext(), false);
135 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700136
137 if (LauncherAppState.PROFILE_STARTUP) {
138 Trace.endSection();
139 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700140 }
141 }
142
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800143 @Override
144 public Cursor query(Uri uri, String[] projection, String selection,
145 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700146 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800147
148 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
149 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
150 qb.setTables(args.table);
151
Romain Guy73b979d2009-06-09 12:57:21 -0700152 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
154 result.setNotificationUri(getContext().getContentResolver(), uri);
155
156 return result;
157 }
158
Adam Cohen091440a2015-03-18 14:16:05 -0700159 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500161 if (values == null) {
162 throw new RuntimeException("Error: attempting to insert null values");
163 }
Adam Cohen71483f42014-05-15 14:04:01 -0700164 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 throw new RuntimeException("Error: attempting to add item without specifying an id");
166 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500167 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700168 return db.insert(table, nullColumnHack, values);
169 }
170
Sunny Goyald1064182015-08-13 12:08:30 -0700171 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700172 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700173 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
174 if (app != null) {
175 app.reloadWorkspace();
176 }
177 }
178 }
179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 @Override
181 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700182 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183 SqlArguments args = new SqlArguments(uri);
184
Sunny Goyald1064182015-08-13 12:08:30 -0700185 // In very limited cases, we support system|signature permission apps to modify the db.
186 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700187 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700188 return null;
189 }
190 }
191
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400193 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700194 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800195 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196
197 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700198 notifyListeners();
199
Sunny Goyalc74e4192015-09-08 14:01:03 -0700200 if (Utilities.ATLEAST_MARSHMALLOW) {
201 reloadLauncherIfExternal();
202 } else {
203 // Deprecated behavior to support legacy devices which rely on provider callbacks.
204 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
205 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
206 app.reloadWorkspace();
207 }
208
209 String notify = uri.getQueryParameter("notify");
210 if (notify == null || "true".equals(notify)) {
211 getContext().getContentResolver().notifyChange(uri, null);
212 }
213 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214 return uri;
215 }
216
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700217 private boolean initializeExternalAdd(ContentValues values) {
218 // 1. Ensure that externally added items have a valid item id
219 long id = mOpenHelper.generateNewItemId();
220 values.put(LauncherSettings.Favorites._ID, id);
221
222 // 2. In the case of an app widget, and if no app widget id is specified, we
223 // attempt allocate and bind the widget.
224 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
225 if (itemType != null &&
226 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
227 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
228
229 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
230 ComponentName cn = ComponentName.unflattenFromString(
231 values.getAsString(Favorites.APPWIDGET_PROVIDER));
232
233 if (cn != null) {
234 try {
235 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
236 .allocateAppWidgetId();
237 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
238 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
239 return false;
240 }
241 } catch (RuntimeException e) {
242 Log.e(TAG, "Failed to initialize external widget", e);
243 return false;
244 }
245 } else {
246 return false;
247 }
248 }
249
250 // Add screen id if not present
251 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
252 SQLiteStatement stmp = null;
253 try {
254 stmp = mOpenHelper.getWritableDatabase().compileStatement(
255 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
256 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
257 stmp.bindLong(1, screenId);
258
259 ContentValues valuesInserted = new ContentValues();
260 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
261 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
262 return true;
263 } catch (Exception e) {
264 return false;
265 } finally {
266 Utilities.closeSilently(stmp);
267 }
268 }
269
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800270 @Override
271 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700272 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800273 SqlArguments args = new SqlArguments(uri);
274
275 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
276 db.beginTransaction();
277 try {
278 int numValues = values.length;
279 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400280 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700281 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
282 return 0;
283 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 }
285 db.setTransactionSuccessful();
286 } finally {
287 db.endTransaction();
288 }
289
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700290 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700291 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 return values.length;
293 }
294
295 @Override
Yura085c8532014-02-11 15:15:29 +0000296 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
297 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700298 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000299 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
300 db.beginTransaction();
301 try {
302 ContentProviderResult[] result = super.applyBatch(operations);
303 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700304 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000305 return result;
306 } finally {
307 db.endTransaction();
308 }
309 }
310
311 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800312 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700313 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800314 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
315
316 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800317
Louis Begina9c21c62016-08-15 15:18:41 -0700318 if (Binder.getCallingPid() != Process.myPid()
319 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
320 String widgetSelection = TextUtils.isEmpty(args.where) ? "1=1" : args.where;
321 widgetSelection = String.format(Locale.ENGLISH, "%1$s = %2$d AND ( %3$s )",
322 Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET, widgetSelection);
323 try (Cursor c = db.query(Favorites.TABLE_NAME, new String[] { Favorites.APPWIDGET_ID },
324 widgetSelection, args.args, null, null, null)) {
325 AppWidgetHost host = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
326 while (c.moveToNext()) {
327 int widgetId = c.getInt(0);
328 if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
329 try {
330 host.deleteAppWidgetId(widgetId);
331 } catch (RuntimeException e) {
332 Log.e(TAG, "Error deleting widget id " + widgetId, e);
333 }
334 }
335 }
336 }
337 }
338 int count = db.delete(args.table, args.where, args.args);
339 if (count > 0) {
340 notifyListeners();
341 reloadLauncherIfExternal();
342 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343 return count;
344 }
345
346 @Override
347 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700348 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
350
Chris Wren1ada10d2013-09-13 18:01:38 -0400351 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
353 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700354 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355
Sunny Goyald1064182015-08-13 12:08:30 -0700356 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 return count;
358 }
359
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700361 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 if (Binder.getCallingUid() != Process.myUid()) {
363 return null;
364 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700365 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700366
367 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700368 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
369 String extractedColors = extras.getString(
370 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
371 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
372 Utilities.getPrefs(getContext()).edit()
373 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
374 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
375 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700376 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700377 Bundle result = new Bundle();
378 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
379 return result;
380 }
Sunny Goyald2497482015-09-22 18:24:19 -0700381 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
382 clearFlagEmptyDbCreated();
383 return null;
384 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700385 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
386 Bundle result = new Bundle();
387 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
388 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
389 return result;
390 }
Sunny Goyald2497482015-09-22 18:24:19 -0700391 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
392 Bundle result = new Bundle();
393 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
394 return result;
395 }
396 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
397 Bundle result = new Bundle();
398 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
399 return result;
400 }
401 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
402 Bundle result = new Bundle();
403 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
404 return result;
405 }
406 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
407 createEmptyDB();
408 return null;
409 }
410 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
411 loadDefaultFavoritesIfNecessary();
412 return null;
413 }
Sunny Goyald2497482015-09-22 18:24:19 -0700414 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800415 // Are you sure? (y/n)
416 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700417 return null;
418 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700419 }
420 return null;
421 }
422
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700423 /**
424 * Deletes any empty folder from the DB.
425 * @return Ids of deleted folders.
426 */
Sunny Goyald2497482015-09-22 18:24:19 -0700427 private ArrayList<Long> deleteEmptyFolders() {
428 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
430 db.beginTransaction();
431 try {
432 // Select folders whose id do not match any container value.
433 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
434 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
435 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
436 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700437 + Favorites.TABLE_NAME + ")";
438 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700439 new String[] {LauncherSettings.Favorites._ID},
440 selection, null, null, null, null);
441 while (c.moveToNext()) {
442 folderIds.add(c.getLong(0));
443 }
444 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700445 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700446 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700447 LauncherSettings.Favorites._ID, folderIds), null);
448 }
449 db.setTransactionSuccessful();
450 } catch (SQLException ex) {
451 Log.e(TAG, ex.getMessage(), ex);
452 folderIds.clear();
453 } finally {
454 db.endTransaction();
455 }
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
Brian Muramatsu5524b492012-10-02 16:55:54 -0700470 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700471 * Clears all the data for a fresh start.
472 */
Sunny Goyald2497482015-09-22 18:24:19 -0700473 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700474 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
475 }
476
Sunny Goyald2497482015-09-22 18:24:19 -0700477 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700478 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700479 }
480
Sunny Goyal42de82f2014-09-26 22:09:29 -0700481 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700482 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700483 * 1) From the app restrictions
484 * 2) From a package provided by play store
485 * 3) From a partner configuration APK, already in the system image
486 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700487 */
Sunny Goyald2497482015-09-22 18:24:19 -0700488 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700489 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700490
Winson Chungc763c4e2013-07-19 13:49:06 -0700491 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500492 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200493
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700494 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
495 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700496 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700497 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700498 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700499 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700500 final Partner partner = Partner.get(getContext().getPackageManager());
501 if (partner != null && partner.hasDefaultLayout()) {
502 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700503 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700504 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700505 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700506 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700507 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700508 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700509 }
510 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700511
Sunny Goyal9d219682014-10-23 14:21:02 -0700512 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700513 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700514 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700515 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800516
517 // There might be some partially restored DB items, due to buggy restore logic in
518 // previous versions of launcher.
519 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700520 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700521 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
522 && usingExternallyProvidedLayout) {
523 // Unable to load external layout. Cleanup and load the internal layout.
524 createEmptyDB();
525 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700526 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700527 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700528 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700529 }
530 }
531
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700532 /**
533 * Creates workspace loader from an XML resource listed in the app restrictions.
534 *
535 * @return the loader if the restrictions are set and the resource exists; null otherwise.
536 */
537 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700538 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700539 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700540 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541 return null;
542 }
543
544 Context ctx = getContext();
545 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
546 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700547 if (bundle == null) {
548 return null;
549 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700550
Sunny Goyal35ca8732015-04-06 10:45:31 -0700551 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700552 if (packageName != null) {
553 try {
554 Resources targetResources = ctx.getPackageManager()
555 .getResourcesForApplication(packageName);
556 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700558 } catch (NameNotFoundException e) {
559 Log.e(TAG, "Target package for restricted profile not found", e);
560 return null;
561 }
562 }
563 return null;
564 }
565
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700566 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700567 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700568 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700569 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700570 mOpenHelper, getContext().getResources(), defaultLayout);
571 }
572
Sunny Goyald3849d12015-10-29 10:28:32 -0700573 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800574 * The class is subclassed in tests to create an in-memory db.
575 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700576 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700577 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 private long mMaxItemId = -1;
580 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800581
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700582 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
583 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700584 // Table creation sometimes fails silently, which leads to a crash loop.
585 // This way, we will try to create a table every time after crash, so the device
586 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700587 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700588 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
589 // This operation is a no-op if the table already exists.
590 addFavoritesTable(getWritableDatabase(), true);
591 addWorkspacesTable(getWritableDatabase(), true);
592 }
593
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700594 initIds();
595 }
596
597 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700598 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700599 */
600 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700601 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700602 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
603 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700604 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700605 }
606
607 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700608 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
609 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700610 if (mMaxItemId == -1) {
611 mMaxItemId = initializeMaxItemId(getWritableDatabase());
612 }
613 if (mMaxScreenId == -1) {
614 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700615 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
617
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 private boolean tableExists(String tableName) {
619 Cursor c = getReadableDatabase().query(
620 true, "sqlite_master", new String[] {"tbl_name"},
621 "tbl_name = ?", new String[] {tableName},
622 null, null, null, null, null);
623 try {
624 return c.getCount() > 0;
625 } finally {
626 c.close();
627 }
628 }
629
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 @Override
631 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800632 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700633
Adam Cohendcd297f2013-06-18 13:13:40 -0700634 mMaxItemId = 1;
635 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700636
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700637 addFavoritesTable(db, false);
638 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800640 // Fresh and clean launcher DB.
641 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800642 onEmptyDbCreated();
643 }
644
645 /**
646 * Overriden in tests.
647 */
648 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700649 // Database was just created, so wipe any previous widgets
650 if (mWidgetHostResetHandler != null) {
651 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700652 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530653 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700654 }
655
Sunny Goyalf076eae2016-01-11 12:25:10 -0800656 // Set the flag for empty DB
657 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700658
659 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800660 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
661 mContext);
662 }
663
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700664 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800665 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
666 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 }
668
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700669 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700670 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700671 }
672
673 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
674 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700675 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800676 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400677 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
678 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700679 ");");
680 }
681
Adam Cohen119285e2014-04-02 16:59:08 -0700682 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700683 // Delete items directly on the workspace who's screen id doesn't exist
684 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
685 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700686 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700687 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700688 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700689 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700690 " AND " +
691 LauncherSettings.Favorites.CONTAINER + " = " +
692 LauncherSettings.Favorites.CONTAINER_DESKTOP;
693 db.execSQL(removeOrphanedDesktopItems);
694
695 // Delete items contained in folders which no longer exist (after above statement)
696 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
697 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700698 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700699 " WHERE " +
700 LauncherSettings.Favorites.CONTAINER + " <> " +
701 LauncherSettings.Favorites.CONTAINER_DESKTOP +
702 " AND "
703 + LauncherSettings.Favorites.CONTAINER + " <> " +
704 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
705 " AND "
706 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700707 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700708 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
709 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
710 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700711 }
712
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713 @Override
714 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700715 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 switch (oldVersion) {
717 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800718 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800719 case 12: {
720 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
721 // to persist workspace screens and their relative order.
722 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700723 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800724 }
725 case 13: {
726 db.beginTransaction();
727 try {
728 // Insert new column for holding widget provider name
729 db.execSQL("ALTER TABLE favorites " +
730 "ADD COLUMN appWidgetProvider TEXT;");
731 db.setTransactionSuccessful();
732 } catch (SQLException ex) {
733 Log.e(TAG, ex.getMessage(), ex);
734 // Old version remains, which means we wipe old data
735 break;
736 } finally {
737 db.endTransaction();
738 }
739 }
740 case 14: {
741 db.beginTransaction();
742 try {
743 // Insert new column for holding update timestamp
744 db.execSQL("ALTER TABLE favorites " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
746 db.execSQL("ALTER TABLE workspaceScreens " +
747 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
748 db.setTransactionSuccessful();
749 } catch (SQLException ex) {
750 Log.e(TAG, ex.getMessage(), ex);
751 // Old version remains, which means we wipe old data
752 break;
753 } finally {
754 db.endTransaction();
755 }
756 }
757 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700758 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 // Old version remains, which means we wipe old data
760 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 }
762 }
763 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700764 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800765 }
766 case 17: {
767 // No-op
768 }
769 case 18: {
770 // Due to a data loss bug, some users may have items associated with screen ids
771 // which no longer exist. Since this can cause other problems, and since the user
772 // will never see these items anyway, we use database upgrade as an opportunity to
773 // clean things up.
774 removeOrphanedItems(db);
775 }
776 case 19: {
777 // Add userId column
778 if (!addProfileColumn(db)) {
779 // Old version remains, which means we wipe old data
780 break;
781 }
782 }
783 case 20:
784 if (!updateFolderItemsRank(db, true)) {
785 break;
786 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800787 case 21:
788 // Recreate workspace table with screen id a primary key
789 if (!recreateWorkspaceTable(db)) {
790 break;
791 }
792 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700793 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
794 // Old version remains, which means we wipe old data
795 break;
796 }
797 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700798 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700799 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700800 case 24:
801 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700802 case 25:
803 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700804 case 26:
805 // QSB was moved to the grid. Clear the first row on screen 0.
806 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
807 !LauncherDbUtils.prepareScreenZeroToHostQsb(db)) {
808 break;
809 }
810 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800811 // DB Upgraded successfully
812 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400813 }
814 }
815
Sunny Goyala2cc6242015-01-14 14:23:02 -0800816 // DB was not upgraded
817 Log.w(TAG, "Destroying all old data.");
818 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800819 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800820
Adam Cohen9b1d0622014-05-21 19:01:57 -0700821 @Override
822 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
823 // This shouldn't happen -- throw our hands up in the air and start over.
824 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
825 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700826 createEmptyDB(db);
827 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700828
Sunny Goyal42de82f2014-09-26 22:09:29 -0700829 /**
830 * Clears all the data for a fresh start.
831 */
832 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700833 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
834 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700835 onCreate(db);
836 }
837
Sunny Goyald2f38192015-02-25 10:46:34 -0800838 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700839 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
840 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
841 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700842 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 db.beginTransaction();
844 Cursor c = null;
845 SQLiteStatement updateStmt = null;
846
847 try {
848 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700849 long userSerial = getDefaultUserSerial();
850 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700851 Favorites._ID,
852 Favorites.INTENT,
853 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
854 null, null, null, null);
855
856 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
857 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
858
859 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
860 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
861
862 while (c.moveToNext()) {
863 String intentDescription = c.getString(intentIndex);
864 Intent intent;
865 try {
866 intent = Intent.parseUri(intentDescription, 0);
867 } catch (URISyntaxException e) {
868 Log.e(TAG, "Unable to parse intent", e);
869 continue;
870 }
871
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700872 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700873 continue;
874 }
875
876 long id = c.getLong(idIndex);
877 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700878 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700879 }
880 db.setTransactionSuccessful();
881 } catch (SQLException ex) {
882 Log.w(TAG, "Error deduping shortcuts", ex);
883 } finally {
884 db.endTransaction();
885 if (c != null) {
886 c.close();
887 }
888 if (updateStmt != null) {
889 updateStmt.close();
890 }
891 }
892 }
893
894 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800895 * Recreates workspace table and migrates data to the new table.
896 */
897 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
898 db.beginTransaction();
899 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700900 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800901 new String[] {LauncherSettings.WorkspaceScreens._ID},
902 null, null, null, null,
903 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
904 ArrayList<Long> sortedIDs = new ArrayList<Long>();
905 long maxId = 0;
906 try {
907 while (c.moveToNext()) {
908 Long id = c.getLong(0);
909 if (!sortedIDs.contains(id)) {
910 sortedIDs.add(id);
911 maxId = Math.max(maxId, id);
912 }
913 }
914 } finally {
915 c.close();
916 }
917
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700918 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700919 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800920
921 // Add all screen ids back
922 int total = sortedIDs.size();
923 for (int i = 0; i < total; i++) {
924 ContentValues values = new ContentValues();
925 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
926 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
927 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700928 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800929 }
930 db.setTransactionSuccessful();
931 mMaxScreenId = maxId;
932 } catch (SQLException ex) {
933 // Old version remains, which means we wipe old data
934 Log.e(TAG, ex.getMessage(), ex);
935 return false;
936 } finally {
937 db.endTransaction();
938 }
939 return true;
940 }
941
Adam Cohen091440a2015-03-18 14:16:05 -0700942 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800943 db.beginTransaction();
944 try {
945 if (addRankColumn) {
946 // Insert new column for holding rank
947 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
948 }
949
950 // Get a map for folder ID to folder width
951 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
952 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
953 + " GROUP BY container;",
954 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
955
956 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800957 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
958 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800959 new Object[] {c.getLong(1) + 1, c.getLong(0)});
960 }
961
962 c.close();
963 db.setTransactionSuccessful();
964 } catch (SQLException ex) {
965 // Old version remains, which means we wipe old data
966 Log.e(TAG, ex.getMessage(), ex);
967 return false;
968 } finally {
969 db.endTransaction();
970 }
971 return true;
972 }
973
Kenny Guyed131872014-04-30 03:02:21 +0100974 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700975 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700976 }
977
978 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100979 db.beginTransaction();
980 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700981 db.execSQL("ALTER TABLE favorites ADD COLUMN "
982 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100983 db.setTransactionSuccessful();
984 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100985 Log.e(TAG, ex.getMessage(), ex);
986 return false;
987 } finally {
988 db.endTransaction();
989 }
990 return true;
991 }
992
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700993 // Generates a new ID to use for an object in your database. This method should be only
994 // called from the main UI thread. As an exception, we do call it when we call the
995 // constructor from the worker thread; however, this doesn't extend until after the
996 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
997 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700998 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700999 public long generateNewItemId() {
1000 if (mMaxItemId < 0) {
1001 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001002 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 mMaxItemId += 1;
1004 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001005 }
1006
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001007 @Override
1008 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001009 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001010 }
1011
Chris Wren5dee7af2013-12-20 17:22:11 -05001012 public void checkId(String table, ContentValues values) {
1013 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001014 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001015 mMaxScreenId = Math.max(id, mMaxScreenId);
1016 } else {
1017 mMaxItemId = Math.max(id, mMaxItemId);
1018 }
1019 }
1020
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001022 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001023 }
1024
1025 // Generates a new ID to use for an workspace screen in your database. This method
1026 // should be only called from the main UI thread. As an exception, we do call it when we
1027 // call the constructor from the worker thread; however, this doesn't extend until after the
1028 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1029 // after that point
1030 public long generateNewScreenId() {
1031 if (mMaxScreenId < 0) {
1032 throw new RuntimeException("Error: max screen id was not initialized");
1033 }
1034 mMaxScreenId += 1;
1035 return mMaxScreenId;
1036 }
1037
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001039 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001040 }
1041
Adam Cohen091440a2015-03-18 14:16:05 -07001042 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001043 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001044 // TODO: Use multiple loaders with fall-back and transaction.
1045 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001046
1047 // Add the screens specified by the items above
1048 Collections.sort(screenIds);
1049 int rank = 0;
1050 ContentValues values = new ContentValues();
1051 for (Long id : screenIds) {
1052 values.clear();
1053 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1054 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001055 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001056 throw new RuntimeException("Failed initialize screen table"
1057 + "from default layout");
1058 }
1059 rank++;
1060 }
1061
1062 // Ensure that the max ids are initialized
1063 mMaxItemId = initializeMaxItemId(db);
1064 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001065
Adam Cohen71483f42014-05-15 14:04:01 -07001066 return count;
1067 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001068 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001069
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001070 /**
1071 * @return the max _id in the provided table.
1072 */
Adam Cohen091440a2015-03-18 14:16:05 -07001073 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001074 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1075 // get the result
1076 long id = -1;
1077 if (c != null && c.moveToNext()) {
1078 id = c.getLong(0);
1079 }
1080 if (c != null) {
1081 c.close();
1082 }
1083
1084 if (id == -1) {
1085 throw new RuntimeException("Error: could not query max id in " + table);
1086 }
1087
1088 return id;
1089 }
1090
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001091 static class SqlArguments {
1092 public final String table;
1093 public final String where;
1094 public final String[] args;
1095
1096 SqlArguments(Uri url, String where, String[] args) {
1097 if (url.getPathSegments().size() == 1) {
1098 this.table = url.getPathSegments().get(0);
1099 this.where = where;
1100 this.args = args;
1101 } else if (url.getPathSegments().size() != 2) {
1102 throw new IllegalArgumentException("Invalid URI: " + url);
1103 } else if (!TextUtils.isEmpty(where)) {
1104 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1105 } else {
1106 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001107 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001108 this.args = null;
1109 }
1110 }
1111
1112 SqlArguments(Uri url) {
1113 if (url.getPathSegments().size() == 1) {
1114 table = url.getPathSegments().get(0);
1115 where = null;
1116 args = null;
1117 } else {
1118 throw new IllegalArgumentException("Invalid URI: " + url);
1119 }
1120 }
1121 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001122
1123 private static class ChangeListenerWrapper implements Handler.Callback {
1124
1125 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1126 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1127 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1128
1129 private LauncherProviderChangeListener mListener;
1130
1131 @Override
1132 public boolean handleMessage(Message msg) {
1133 if (mListener != null) {
1134 switch (msg.what) {
1135 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001136 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001137 break;
1138 case MSG_EXTRACTED_COLORS_CHANGED:
1139 mListener.onExtractedColorsChanged();
1140 break;
1141 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001142 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001143 break;
1144 }
1145 }
1146 return true;
1147 }
1148 }
Adam Cohen72960972014-01-15 18:13:55 -08001149}