blob: f3d949326c6c0aae333051d042d9eba0b6c4f2b5 [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 Goyalda4fe1a2016-05-26 16:05:17 -0700652 mWidgetHostResetHandler.sendMessage(Message.obtain(
653 mWidgetHostResetHandler,
654 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET,
655 mContext
656 ));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700657 }
658
Sunny Goyalf076eae2016-01-11 12:25:10 -0800659 // Set the flag for empty DB
660 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700661
662 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800663 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
664 mContext);
665 }
666
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700667 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800668 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
669 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670 }
671
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700672 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700673 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700674 }
675
676 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
677 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700678 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800679 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400680 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
681 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700682 ");");
683 }
684
Adam Cohen119285e2014-04-02 16:59:08 -0700685 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700686 // Delete items directly on the workspace who's screen id doesn't exist
687 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
688 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700689 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700690 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700691 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700692 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700693 " AND " +
694 LauncherSettings.Favorites.CONTAINER + " = " +
695 LauncherSettings.Favorites.CONTAINER_DESKTOP;
696 db.execSQL(removeOrphanedDesktopItems);
697
698 // Delete items contained in folders which no longer exist (after above statement)
699 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
700 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700701 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700702 " WHERE " +
703 LauncherSettings.Favorites.CONTAINER + " <> " +
704 LauncherSettings.Favorites.CONTAINER_DESKTOP +
705 " AND "
706 + LauncherSettings.Favorites.CONTAINER + " <> " +
707 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
708 " AND "
709 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700710 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700711 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
712 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
713 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700714 }
715
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716 @Override
717 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700718 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800719 switch (oldVersion) {
720 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800721 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800722 case 12: {
723 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
724 // to persist workspace screens and their relative order.
725 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700726 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 }
728 case 13: {
729 db.beginTransaction();
730 try {
731 // Insert new column for holding widget provider name
732 db.execSQL("ALTER TABLE favorites " +
733 "ADD COLUMN appWidgetProvider TEXT;");
734 db.setTransactionSuccessful();
735 } catch (SQLException ex) {
736 Log.e(TAG, ex.getMessage(), ex);
737 // Old version remains, which means we wipe old data
738 break;
739 } finally {
740 db.endTransaction();
741 }
742 }
743 case 14: {
744 db.beginTransaction();
745 try {
746 // Insert new column for holding update timestamp
747 db.execSQL("ALTER TABLE favorites " +
748 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
749 db.execSQL("ALTER TABLE workspaceScreens " +
750 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
751 db.setTransactionSuccessful();
752 } catch (SQLException ex) {
753 Log.e(TAG, ex.getMessage(), ex);
754 // Old version remains, which means we wipe old data
755 break;
756 } finally {
757 db.endTransaction();
758 }
759 }
760 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700761 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800762 // Old version remains, which means we wipe old data
763 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 }
765 }
766 case 16: {
767 // We use the db version upgrade here to identify users who may not have seen
768 // clings yet (because they weren't available), but for whom the clings are now
769 // available (tablet users). Because one of the possible cling flows (migration)
770 // is very destructive (wipes out workspaces), we want to prevent this from showing
771 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800772 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800773 }
774 case 17: {
775 // No-op
776 }
777 case 18: {
778 // Due to a data loss bug, some users may have items associated with screen ids
779 // which no longer exist. Since this can cause other problems, and since the user
780 // will never see these items anyway, we use database upgrade as an opportunity to
781 // clean things up.
782 removeOrphanedItems(db);
783 }
784 case 19: {
785 // Add userId column
786 if (!addProfileColumn(db)) {
787 // Old version remains, which means we wipe old data
788 break;
789 }
790 }
791 case 20:
792 if (!updateFolderItemsRank(db, true)) {
793 break;
794 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800795 case 21:
796 // Recreate workspace table with screen id a primary key
797 if (!recreateWorkspaceTable(db)) {
798 break;
799 }
800 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700801 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
802 // Old version remains, which means we wipe old data
803 break;
804 }
805 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700806 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700807 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700808 case 24:
809 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700810 case 25:
811 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700812 case 26:
813 // QSB was moved to the grid. Clear the first row on screen 0.
814 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
815 !LauncherDbUtils.prepareScreenZeroToHostQsb(db)) {
816 break;
817 }
818 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800819 // DB Upgraded successfully
820 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400821 }
822 }
823
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 // DB was not upgraded
825 Log.w(TAG, "Destroying all old data.");
826 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800827 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800828
Adam Cohen9b1d0622014-05-21 19:01:57 -0700829 @Override
830 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
831 // This shouldn't happen -- throw our hands up in the air and start over.
832 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
833 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700834 createEmptyDB(db);
835 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700836
Sunny Goyal42de82f2014-09-26 22:09:29 -0700837 /**
838 * Clears all the data for a fresh start.
839 */
840 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700841 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
842 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700843 onCreate(db);
844 }
845
Sunny Goyald2f38192015-02-25 10:46:34 -0800846 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700847 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
848 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
849 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700850 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700851 db.beginTransaction();
852 Cursor c = null;
853 SQLiteStatement updateStmt = null;
854
855 try {
856 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700857 long userSerial = getDefaultUserSerial();
858 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700859 Favorites._ID,
860 Favorites.INTENT,
861 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
862 null, null, null, null);
863
864 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
865 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
866
867 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
868 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
869
870 while (c.moveToNext()) {
871 String intentDescription = c.getString(intentIndex);
872 Intent intent;
873 try {
874 intent = Intent.parseUri(intentDescription, 0);
875 } catch (URISyntaxException e) {
876 Log.e(TAG, "Unable to parse intent", e);
877 continue;
878 }
879
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700880 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700881 continue;
882 }
883
884 long id = c.getLong(idIndex);
885 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700886 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700887 }
888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
890 Log.w(TAG, "Error deduping shortcuts", ex);
891 } finally {
892 db.endTransaction();
893 if (c != null) {
894 c.close();
895 }
896 if (updateStmt != null) {
897 updateStmt.close();
898 }
899 }
900 }
901
902 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800903 * Recreates workspace table and migrates data to the new table.
904 */
905 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
906 db.beginTransaction();
907 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700908 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800909 new String[] {LauncherSettings.WorkspaceScreens._ID},
910 null, null, null, null,
911 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
912 ArrayList<Long> sortedIDs = new ArrayList<Long>();
913 long maxId = 0;
914 try {
915 while (c.moveToNext()) {
916 Long id = c.getLong(0);
917 if (!sortedIDs.contains(id)) {
918 sortedIDs.add(id);
919 maxId = Math.max(maxId, id);
920 }
921 }
922 } finally {
923 c.close();
924 }
925
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700926 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700927 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800928
929 // Add all screen ids back
930 int total = sortedIDs.size();
931 for (int i = 0; i < total; i++) {
932 ContentValues values = new ContentValues();
933 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
934 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
935 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700936 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800937 }
938 db.setTransactionSuccessful();
939 mMaxScreenId = maxId;
940 } catch (SQLException ex) {
941 // Old version remains, which means we wipe old data
942 Log.e(TAG, ex.getMessage(), ex);
943 return false;
944 } finally {
945 db.endTransaction();
946 }
947 return true;
948 }
949
Adam Cohen091440a2015-03-18 14:16:05 -0700950 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800951 db.beginTransaction();
952 try {
953 if (addRankColumn) {
954 // Insert new column for holding rank
955 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
956 }
957
958 // Get a map for folder ID to folder width
959 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
960 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
961 + " GROUP BY container;",
962 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
963
964 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800965 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
966 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800967 new Object[] {c.getLong(1) + 1, c.getLong(0)});
968 }
969
970 c.close();
971 db.setTransactionSuccessful();
972 } catch (SQLException ex) {
973 // Old version remains, which means we wipe old data
974 Log.e(TAG, ex.getMessage(), ex);
975 return false;
976 } finally {
977 db.endTransaction();
978 }
979 return true;
980 }
981
Kenny Guyed131872014-04-30 03:02:21 +0100982 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700983 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700984 }
985
986 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100987 db.beginTransaction();
988 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700989 db.execSQL("ALTER TABLE favorites ADD COLUMN "
990 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100991 db.setTransactionSuccessful();
992 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100993 Log.e(TAG, ex.getMessage(), ex);
994 return false;
995 } finally {
996 db.endTransaction();
997 }
998 return true;
999 }
1000
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 // Generates a new ID to use for an object in your database. This method should be only
1002 // called from the main UI thread. As an exception, we do call it when we call the
1003 // constructor from the worker thread; however, this doesn't extend until after the
1004 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1005 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001006 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 public long generateNewItemId() {
1008 if (mMaxItemId < 0) {
1009 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001010 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 mMaxItemId += 1;
1012 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 }
1014
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001015 @Override
1016 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001017 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001018 }
1019
Chris Wren5dee7af2013-12-20 17:22:11 -05001020 public void checkId(String table, ContentValues values) {
1021 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001022 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001023 mMaxScreenId = Math.max(id, mMaxScreenId);
1024 } else {
1025 mMaxItemId = Math.max(id, mMaxItemId);
1026 }
1027 }
1028
Adam Cohendcd297f2013-06-18 13:13:40 -07001029 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001030 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001031 }
1032
1033 // Generates a new ID to use for an workspace screen in your database. This method
1034 // should be only called from the main UI thread. As an exception, we do call it when we
1035 // call the constructor from the worker thread; however, this doesn't extend until after the
1036 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1037 // after that point
1038 public long generateNewScreenId() {
1039 if (mMaxScreenId < 0) {
1040 throw new RuntimeException("Error: max screen id was not initialized");
1041 }
1042 mMaxScreenId += 1;
1043 return mMaxScreenId;
1044 }
1045
Adam Cohendcd297f2013-06-18 13:13:40 -07001046 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001047 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001048 }
1049
Adam Cohen091440a2015-03-18 14:16:05 -07001050 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001051 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001052 // TODO: Use multiple loaders with fall-back and transaction.
1053 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001054
1055 // Add the screens specified by the items above
1056 Collections.sort(screenIds);
1057 int rank = 0;
1058 ContentValues values = new ContentValues();
1059 for (Long id : screenIds) {
1060 values.clear();
1061 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1062 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001063 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001064 throw new RuntimeException("Failed initialize screen table"
1065 + "from default layout");
1066 }
1067 rank++;
1068 }
1069
1070 // Ensure that the max ids are initialized
1071 mMaxItemId = initializeMaxItemId(db);
1072 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001073
Adam Cohen71483f42014-05-15 14:04:01 -07001074 return count;
1075 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001076 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001077
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001078 /**
1079 * @return the max _id in the provided table.
1080 */
Adam Cohen091440a2015-03-18 14:16:05 -07001081 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001082 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1083 // get the result
1084 long id = -1;
1085 if (c != null && c.moveToNext()) {
1086 id = c.getLong(0);
1087 }
1088 if (c != null) {
1089 c.close();
1090 }
1091
1092 if (id == -1) {
1093 throw new RuntimeException("Error: could not query max id in " + table);
1094 }
1095
1096 return id;
1097 }
1098
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001099 static class SqlArguments {
1100 public final String table;
1101 public final String where;
1102 public final String[] args;
1103
1104 SqlArguments(Uri url, String where, String[] args) {
1105 if (url.getPathSegments().size() == 1) {
1106 this.table = url.getPathSegments().get(0);
1107 this.where = where;
1108 this.args = args;
1109 } else if (url.getPathSegments().size() != 2) {
1110 throw new IllegalArgumentException("Invalid URI: " + url);
1111 } else if (!TextUtils.isEmpty(where)) {
1112 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1113 } else {
1114 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001115 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001116 this.args = null;
1117 }
1118 }
1119
1120 SqlArguments(Uri url) {
1121 if (url.getPathSegments().size() == 1) {
1122 table = url.getPathSegments().get(0);
1123 where = null;
1124 args = null;
1125 } else {
1126 throw new IllegalArgumentException("Invalid URI: " + url);
1127 }
1128 }
1129 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001130
1131 private static class ChangeListenerWrapper implements Handler.Callback {
1132
1133 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1134 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1135 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1136
1137 private LauncherProviderChangeListener mListener;
1138
1139 @Override
1140 public boolean handleMessage(Message msg) {
1141 if (mListener != null) {
1142 switch (msg.what) {
1143 case MSG_LAUNCHER_PROVIDER_CHANGED:
1144 mListener.onLauncherProviderChange();
1145 break;
1146 case MSG_EXTRACTED_COLORS_CHANGED:
1147 mListener.onExtractedColorsChanged();
1148 break;
1149 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07001150 Context context = (Context) msg.obj;
1151 if (context != null) {
1152 context.sendBroadcast(new Intent(Launcher.ACTION_APPWIDGET_HOST_RESET)
1153 .setPackage(context.getPackageName()));
1154 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001155 break;
1156 }
1157 }
1158 return true;
1159 }
1160 }
Adam Cohen72960972014-01-15 18:13:55 -08001161}