blob: dfb8ba277694b8848b74ae3713b8f46e6eb00846 [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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070045import android.os.Handler;
46import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Process;
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;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050051import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070052
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
54import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070055import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.UserHandleCompat;
57import com.android.launcher3.compat.UserManagerCompat;
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 Goyale8f7d5a2016-05-24 11:30:14 -070060import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070061import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070062import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070063import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070065
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070068import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050069import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070072 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080073 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
Sunny Goyal5c97f512015-05-19 16:03:28 -070075 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Sunny Goyale5bb7052015-07-27 14:36:07 -070077 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070078
Sunny Goyale87e6ab2014-11-21 22:42:53 -080079 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070081 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
82
Sunny Goyalb5b55c82016-05-10 12:28:59 -070083 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
84 private Handler mListenerHandler;
85
Sunny Goyalf076eae2016-01-11 12:25:10 -080086 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
88 @Override
89 public boolean onCreate() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -070090 mListenerHandler = new Handler(mListenerWrapper);
91
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093 return true;
94 }
95
Sunny Goyald3849d12015-10-29 10:28:32 -070096 /**
97 * Sets a provider listener.
98 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700100 Preconditions.assertUIThread();
101 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
Sunny Goyalf076eae2016-01-11 12:25:10 -0800114 /**
115 * Overridden in tests
116 */
117 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700118 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700119 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700120
121 if (RestoreDbTask.isPending(getContext())) {
122 if (!RestoreDbTask.performRestore(mOpenHelper)) {
123 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
124 }
125 // Set is pending to false irrespective of the result, so that it doesn't get
126 // executed again.
127 RestoreDbTask.setPending(getContext(), false);
128 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700129 }
130 }
131
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 @Override
133 public Cursor query(Uri uri, String[] projection, String selection,
134 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700135 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
137 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
138 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
139 qb.setTables(args.table);
140
Romain Guy73b979d2009-06-09 12:57:21 -0700141 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800142 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
143 result.setNotificationUri(getContext().getContentResolver(), uri);
144
145 return result;
146 }
147
Adam Cohen091440a2015-03-18 14:16:05 -0700148 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500150 if (values == null) {
151 throw new RuntimeException("Error: attempting to insert null values");
152 }
Adam Cohen71483f42014-05-15 14:04:01 -0700153 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 throw new RuntimeException("Error: attempting to add item without specifying an id");
155 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500156 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 return db.insert(table, nullColumnHack, values);
158 }
159
Sunny Goyald1064182015-08-13 12:08:30 -0700160 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700161 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700162 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
163 if (app != null) {
164 app.reloadWorkspace();
165 }
166 }
167 }
168
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800169 @Override
170 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700171 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 SqlArguments args = new SqlArguments(uri);
173
Sunny Goyald1064182015-08-13 12:08:30 -0700174 // In very limited cases, we support system|signature permission apps to modify the db.
175 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700176 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700177 return null;
178 }
179 }
180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400182 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700183 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800184 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185
186 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700187 notifyListeners();
188
Sunny Goyalc74e4192015-09-08 14:01:03 -0700189 if (Utilities.ATLEAST_MARSHMALLOW) {
190 reloadLauncherIfExternal();
191 } else {
192 // Deprecated behavior to support legacy devices which rely on provider callbacks.
193 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
194 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
195 app.reloadWorkspace();
196 }
197
198 String notify = uri.getQueryParameter("notify");
199 if (notify == null || "true".equals(notify)) {
200 getContext().getContentResolver().notifyChange(uri, null);
201 }
202 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 return uri;
204 }
205
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700206 private boolean initializeExternalAdd(ContentValues values) {
207 // 1. Ensure that externally added items have a valid item id
208 long id = mOpenHelper.generateNewItemId();
209 values.put(LauncherSettings.Favorites._ID, id);
210
211 // 2. In the case of an app widget, and if no app widget id is specified, we
212 // attempt allocate and bind the widget.
213 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
214 if (itemType != null &&
215 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
216 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
217
218 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
219 ComponentName cn = ComponentName.unflattenFromString(
220 values.getAsString(Favorites.APPWIDGET_PROVIDER));
221
222 if (cn != null) {
223 try {
224 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
225 .allocateAppWidgetId();
226 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
227 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
228 return false;
229 }
230 } catch (RuntimeException e) {
231 Log.e(TAG, "Failed to initialize external widget", e);
232 return false;
233 }
234 } else {
235 return false;
236 }
237 }
238
239 // Add screen id if not present
240 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
241 SQLiteStatement stmp = null;
242 try {
243 stmp = mOpenHelper.getWritableDatabase().compileStatement(
244 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
245 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
246 stmp.bindLong(1, screenId);
247
248 ContentValues valuesInserted = new ContentValues();
249 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
250 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
251 return true;
252 } catch (Exception e) {
253 return false;
254 } finally {
255 Utilities.closeSilently(stmp);
256 }
257 }
258
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800259 @Override
260 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700261 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800262 SqlArguments args = new SqlArguments(uri);
263
264 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
265 db.beginTransaction();
266 try {
267 int numValues = values.length;
268 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400269 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700270 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
271 return 0;
272 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800273 }
274 db.setTransactionSuccessful();
275 } finally {
276 db.endTransaction();
277 }
278
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700279 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700280 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800281 return values.length;
282 }
283
284 @Override
Yura085c8532014-02-11 15:15:29 +0000285 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
286 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700287 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000288 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
289 db.beginTransaction();
290 try {
291 ContentProviderResult[] result = super.applyBatch(operations);
292 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700293 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000294 return result;
295 } finally {
296 db.endTransaction();
297 }
298 }
299
300 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700302 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
304
305 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
306 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700307 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800308
Sunny Goyald1064182015-08-13 12:08:30 -0700309 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 return count;
311 }
312
313 @Override
314 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700315 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800316 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
317
Chris Wren1ada10d2013-09-13 18:01:38 -0400318 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800319 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
320 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700321 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322
Sunny Goyald1064182015-08-13 12:08:30 -0700323 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 return count;
325 }
326
Sunny Goyal7779d622015-06-11 16:18:39 -0700327 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700328 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700329 if (Binder.getCallingUid() != Process.myUid()) {
330 return null;
331 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700332 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700333
334 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700335 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
336 String extractedColors = extras.getString(
337 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
338 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
339 Utilities.getPrefs(getContext()).edit()
340 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
341 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
342 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700343 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700344 Bundle result = new Bundle();
345 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
346 return result;
347 }
Sunny Goyald2497482015-09-22 18:24:19 -0700348 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
349 clearFlagEmptyDbCreated();
350 return null;
351 }
352 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
353 Bundle result = new Bundle();
354 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
355 return result;
356 }
357 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
358 Bundle result = new Bundle();
359 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
360 return result;
361 }
362 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
363 Bundle result = new Bundle();
364 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
365 return result;
366 }
367 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
368 createEmptyDB();
369 return null;
370 }
371 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
372 loadDefaultFavoritesIfNecessary();
373 return null;
374 }
Sunny Goyald2497482015-09-22 18:24:19 -0700375 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
376 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
377 return null;
378 }
379 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
380 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
381 return null;
382 }
383 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800384 // Are you sure? (y/n)
385 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700386 return null;
387 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700388 }
389 return null;
390 }
391
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700392 /**
393 * Deletes any empty folder from the DB.
394 * @return Ids of deleted folders.
395 */
Sunny Goyald2497482015-09-22 18:24:19 -0700396 private ArrayList<Long> deleteEmptyFolders() {
397 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700398 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
399 db.beginTransaction();
400 try {
401 // Select folders whose id do not match any container value.
402 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
403 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
404 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
405 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700406 + Favorites.TABLE_NAME + ")";
407 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700408 new String[] {LauncherSettings.Favorites._ID},
409 selection, null, null, null, null);
410 while (c.moveToNext()) {
411 folderIds.add(c.getLong(0));
412 }
413 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700414 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700415 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700416 LauncherSettings.Favorites._ID, folderIds), null);
417 }
418 db.setTransactionSuccessful();
419 } catch (SQLException ex) {
420 Log.e(TAG, ex.getMessage(), ex);
421 folderIds.clear();
422 } finally {
423 db.endTransaction();
424 }
425 return folderIds;
426 }
427
Sunny Goyalf076eae2016-01-11 12:25:10 -0800428 /**
429 * Overridden in tests
430 */
431 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400432 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400433 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700434 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400435 }
436
Adam Cohen091440a2015-03-18 14:16:05 -0700437 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400438 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800439 }
440
Brian Muramatsu5524b492012-10-02 16:55:54 -0700441 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700442 * Clears all the data for a fresh start.
443 */
Sunny Goyald2497482015-09-22 18:24:19 -0700444 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700445 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
446 }
447
Sunny Goyald2497482015-09-22 18:24:19 -0700448 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700449 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700450 }
451
Sunny Goyal42de82f2014-09-26 22:09:29 -0700452 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700453 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700454 * 1) From the app restrictions
455 * 2) From a package provided by play store
456 * 3) From a partner configuration APK, already in the system image
457 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700458 */
Sunny Goyald2497482015-09-22 18:24:19 -0700459 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700460 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700461
Winson Chungc763c4e2013-07-19 13:49:06 -0700462 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500463 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200464
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700465 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
466 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700467 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700468 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700469 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700470 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700471 final Partner partner = Partner.get(getContext().getPackageManager());
472 if (partner != null && partner.hasDefaultLayout()) {
473 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700474 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700475 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700476 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700477 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700478 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700480 }
481 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700482
Sunny Goyal9d219682014-10-23 14:21:02 -0700483 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700484 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700485 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700486 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800487
488 // There might be some partially restored DB items, due to buggy restore logic in
489 // previous versions of launcher.
490 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700491 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700492 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
493 && usingExternallyProvidedLayout) {
494 // Unable to load external layout. Cleanup and load the internal layout.
495 createEmptyDB();
496 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700497 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700498 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700499 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700500 }
501 }
502
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 /**
504 * Creates workspace loader from an XML resource listed in the app restrictions.
505 *
506 * @return the loader if the restrictions are set and the resource exists; null otherwise.
507 */
508 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700509 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700510 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700511 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512 return null;
513 }
514
515 Context ctx = getContext();
516 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
517 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700518 if (bundle == null) {
519 return null;
520 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700521
Sunny Goyal35ca8732015-04-06 10:45:31 -0700522 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700523 if (packageName != null) {
524 try {
525 Resources targetResources = ctx.getPackageManager()
526 .getResourcesForApplication(packageName);
527 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700528 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700529 } catch (NameNotFoundException e) {
530 Log.e(TAG, "Target package for restricted profile not found", e);
531 return null;
532 }
533 }
534 return null;
535 }
536
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700537 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700538 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700539 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700540 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700541 mOpenHelper, getContext().getResources(), defaultLayout);
542 }
543
Sunny Goyald3849d12015-10-29 10:28:32 -0700544 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800545 * The class is subclassed in tests to create an in-memory db.
546 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700547 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700550 private long mMaxItemId = -1;
551 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700553 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
554 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700555 // Table creation sometimes fails silently, which leads to a crash loop.
556 // This way, we will try to create a table every time after crash, so the device
557 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700558 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700559 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
560 // This operation is a no-op if the table already exists.
561 addFavoritesTable(getWritableDatabase(), true);
562 addWorkspacesTable(getWritableDatabase(), true);
563 }
564
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700565 initIds();
566 }
567
568 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700569 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700570 */
571 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700572 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700573 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
574 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700575 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700576 }
577
578 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700579 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
580 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700581 if (mMaxItemId == -1) {
582 mMaxItemId = initializeMaxItemId(getWritableDatabase());
583 }
584 if (mMaxScreenId == -1) {
585 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700586 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587 }
588
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700589 private boolean tableExists(String tableName) {
590 Cursor c = getReadableDatabase().query(
591 true, "sqlite_master", new String[] {"tbl_name"},
592 "tbl_name = ?", new String[] {tableName},
593 null, null, null, null, null);
594 try {
595 return c.getCount() > 0;
596 } finally {
597 c.close();
598 }
599 }
600
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 @Override
602 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800603 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700604
Adam Cohendcd297f2013-06-18 13:13:40 -0700605 mMaxItemId = 1;
606 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700607
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700608 addFavoritesTable(db, false);
609 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800611 // Fresh and clean launcher DB.
612 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800613 onEmptyDbCreated();
614 }
615
616 /**
617 * Overriden in tests.
618 */
619 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700620 // Database was just created, so wipe any previous widgets
621 if (mWidgetHostResetHandler != null) {
622 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyalda4fe1a2016-05-26 16:05:17 -0700623 mWidgetHostResetHandler.sendMessage(Message.obtain(
624 mWidgetHostResetHandler,
625 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET,
626 mContext
627 ));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700628 }
629
Sunny Goyalf076eae2016-01-11 12:25:10 -0800630 // Set the flag for empty DB
631 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700632
633 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800634 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
635 mContext);
636 }
637
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700638 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800639 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
640 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641 }
642
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700644 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700645 }
646
647 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
648 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700649 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800650 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400651 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
652 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 ");");
654 }
655
Adam Cohen119285e2014-04-02 16:59:08 -0700656 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700657 // Delete items directly on the workspace who's screen id doesn't exist
658 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
659 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700660 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700661 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700662 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700663 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700664 " AND " +
665 LauncherSettings.Favorites.CONTAINER + " = " +
666 LauncherSettings.Favorites.CONTAINER_DESKTOP;
667 db.execSQL(removeOrphanedDesktopItems);
668
669 // Delete items contained in folders which no longer exist (after above statement)
670 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
671 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700672 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 " WHERE " +
674 LauncherSettings.Favorites.CONTAINER + " <> " +
675 LauncherSettings.Favorites.CONTAINER_DESKTOP +
676 " AND "
677 + LauncherSettings.Favorites.CONTAINER + " <> " +
678 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
679 " AND "
680 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700681 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700682 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
683 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
684 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700685 }
686
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 @Override
688 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700689 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800690 switch (oldVersion) {
691 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800692 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800693 case 12: {
694 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
695 // to persist workspace screens and their relative order.
696 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700697 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800698 }
699 case 13: {
700 db.beginTransaction();
701 try {
702 // Insert new column for holding widget provider name
703 db.execSQL("ALTER TABLE favorites " +
704 "ADD COLUMN appWidgetProvider TEXT;");
705 db.setTransactionSuccessful();
706 } catch (SQLException ex) {
707 Log.e(TAG, ex.getMessage(), ex);
708 // Old version remains, which means we wipe old data
709 break;
710 } finally {
711 db.endTransaction();
712 }
713 }
714 case 14: {
715 db.beginTransaction();
716 try {
717 // Insert new column for holding update timestamp
718 db.execSQL("ALTER TABLE favorites " +
719 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
720 db.execSQL("ALTER TABLE workspaceScreens " +
721 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
722 db.setTransactionSuccessful();
723 } catch (SQLException ex) {
724 Log.e(TAG, ex.getMessage(), ex);
725 // Old version remains, which means we wipe old data
726 break;
727 } finally {
728 db.endTransaction();
729 }
730 }
731 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700732 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 // Old version remains, which means we wipe old data
734 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 }
736 }
737 case 16: {
738 // We use the db version upgrade here to identify users who may not have seen
739 // clings yet (because they weren't available), but for whom the clings are now
740 // available (tablet users). Because one of the possible cling flows (migration)
741 // is very destructive (wipes out workspaces), we want to prevent this from showing
742 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800743 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800744 }
745 case 17: {
746 // No-op
747 }
748 case 18: {
749 // Due to a data loss bug, some users may have items associated with screen ids
750 // which no longer exist. Since this can cause other problems, and since the user
751 // will never see these items anyway, we use database upgrade as an opportunity to
752 // clean things up.
753 removeOrphanedItems(db);
754 }
755 case 19: {
756 // Add userId column
757 if (!addProfileColumn(db)) {
758 // Old version remains, which means we wipe old data
759 break;
760 }
761 }
762 case 20:
763 if (!updateFolderItemsRank(db, true)) {
764 break;
765 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800766 case 21:
767 // Recreate workspace table with screen id a primary key
768 if (!recreateWorkspaceTable(db)) {
769 break;
770 }
771 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700772 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
773 // Old version remains, which means we wipe old data
774 break;
775 }
776 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700777 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700778 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700779 case 24:
780 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700781 case 25:
782 convertShortcutsToLauncherActivities(db);
783 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800784 // DB Upgraded successfully
785 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400786 }
787 }
788
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 // DB was not upgraded
790 Log.w(TAG, "Destroying all old data.");
791 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800792 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800793
Adam Cohen9b1d0622014-05-21 19:01:57 -0700794 @Override
795 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
796 // This shouldn't happen -- throw our hands up in the air and start over.
797 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
798 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700799 createEmptyDB(db);
800 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700801
Sunny Goyal42de82f2014-09-26 22:09:29 -0700802 /**
803 * Clears all the data for a fresh start.
804 */
805 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700806 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
807 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700808 onCreate(db);
809 }
810
Sunny Goyald2f38192015-02-25 10:46:34 -0800811 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700812 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
813 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
814 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700815 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 db.beginTransaction();
817 Cursor c = null;
818 SQLiteStatement updateStmt = null;
819
820 try {
821 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700822 long userSerial = getDefaultUserSerial();
823 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700824 Favorites._ID,
825 Favorites.INTENT,
826 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
827 null, null, null, null);
828
829 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
830 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
831
832 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
833 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
834
835 while (c.moveToNext()) {
836 String intentDescription = c.getString(intentIndex);
837 Intent intent;
838 try {
839 intent = Intent.parseUri(intentDescription, 0);
840 } catch (URISyntaxException e) {
841 Log.e(TAG, "Unable to parse intent", e);
842 continue;
843 }
844
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700845 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700846 continue;
847 }
848
849 long id = c.getLong(idIndex);
850 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700851 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 }
853 db.setTransactionSuccessful();
854 } catch (SQLException ex) {
855 Log.w(TAG, "Error deduping shortcuts", ex);
856 } finally {
857 db.endTransaction();
858 if (c != null) {
859 c.close();
860 }
861 if (updateStmt != null) {
862 updateStmt.close();
863 }
864 }
865 }
866
867 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800868 * Recreates workspace table and migrates data to the new table.
869 */
870 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
871 db.beginTransaction();
872 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700873 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800874 new String[] {LauncherSettings.WorkspaceScreens._ID},
875 null, null, null, null,
876 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
877 ArrayList<Long> sortedIDs = new ArrayList<Long>();
878 long maxId = 0;
879 try {
880 while (c.moveToNext()) {
881 Long id = c.getLong(0);
882 if (!sortedIDs.contains(id)) {
883 sortedIDs.add(id);
884 maxId = Math.max(maxId, id);
885 }
886 }
887 } finally {
888 c.close();
889 }
890
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700891 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700892 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800893
894 // Add all screen ids back
895 int total = sortedIDs.size();
896 for (int i = 0; i < total; i++) {
897 ContentValues values = new ContentValues();
898 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
899 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
900 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700901 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800902 }
903 db.setTransactionSuccessful();
904 mMaxScreenId = maxId;
905 } catch (SQLException ex) {
906 // Old version remains, which means we wipe old data
907 Log.e(TAG, ex.getMessage(), ex);
908 return false;
909 } finally {
910 db.endTransaction();
911 }
912 return true;
913 }
914
Adam Cohen091440a2015-03-18 14:16:05 -0700915 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800916 db.beginTransaction();
917 try {
918 if (addRankColumn) {
919 // Insert new column for holding rank
920 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
921 }
922
923 // Get a map for folder ID to folder width
924 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
925 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
926 + " GROUP BY container;",
927 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
928
929 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800930 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
931 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800932 new Object[] {c.getLong(1) + 1, c.getLong(0)});
933 }
934
935 c.close();
936 db.setTransactionSuccessful();
937 } catch (SQLException ex) {
938 // Old version remains, which means we wipe old data
939 Log.e(TAG, ex.getMessage(), ex);
940 return false;
941 } finally {
942 db.endTransaction();
943 }
944 return true;
945 }
946
Kenny Guyed131872014-04-30 03:02:21 +0100947 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700948 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700949 }
950
951 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100952 db.beginTransaction();
953 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700954 db.execSQL("ALTER TABLE favorites ADD COLUMN "
955 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100956 db.setTransactionSuccessful();
957 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100958 Log.e(TAG, ex.getMessage(), ex);
959 return false;
960 } finally {
961 db.endTransaction();
962 }
963 return true;
964 }
965
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700966 // Generates a new ID to use for an object in your database. This method should be only
967 // called from the main UI thread. As an exception, we do call it when we call the
968 // constructor from the worker thread; however, this doesn't extend until after the
969 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
970 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700971 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700972 public long generateNewItemId() {
973 if (mMaxItemId < 0) {
974 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700975 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700976 mMaxItemId += 1;
977 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700978 }
979
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700980 @Override
981 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700982 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700983 }
984
Chris Wren5dee7af2013-12-20 17:22:11 -0500985 public void checkId(String table, ContentValues values) {
986 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700987 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500988 mMaxScreenId = Math.max(id, mMaxScreenId);
989 } else {
990 mMaxItemId = Math.max(id, mMaxItemId);
991 }
992 }
993
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700995 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 }
997
998 // Generates a new ID to use for an workspace screen in your database. This method
999 // should be only called from the main UI thread. As an exception, we do call it when we
1000 // call the constructor from the worker thread; however, this doesn't extend until after the
1001 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1002 // after that point
1003 public long generateNewScreenId() {
1004 if (mMaxScreenId < 0) {
1005 throw new RuntimeException("Error: max screen id was not initialized");
1006 }
1007 mMaxScreenId += 1;
1008 return mMaxScreenId;
1009 }
1010
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001012 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001013 }
1014
Adam Cohen091440a2015-03-18 14:16:05 -07001015 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001016 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001017 // TODO: Use multiple loaders with fall-back and transaction.
1018 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001019
1020 // Add the screens specified by the items above
1021 Collections.sort(screenIds);
1022 int rank = 0;
1023 ContentValues values = new ContentValues();
1024 for (Long id : screenIds) {
1025 values.clear();
1026 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1027 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001028 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001029 throw new RuntimeException("Failed initialize screen table"
1030 + "from default layout");
1031 }
1032 rank++;
1033 }
1034
1035 // Ensure that the max ids are initialized
1036 mMaxItemId = initializeMaxItemId(db);
1037 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001038
Adam Cohen71483f42014-05-15 14:04:01 -07001039 return count;
1040 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001041 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001042
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001043 /**
1044 * @return the max _id in the provided table.
1045 */
Adam Cohen091440a2015-03-18 14:16:05 -07001046 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001047 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1048 // get the result
1049 long id = -1;
1050 if (c != null && c.moveToNext()) {
1051 id = c.getLong(0);
1052 }
1053 if (c != null) {
1054 c.close();
1055 }
1056
1057 if (id == -1) {
1058 throw new RuntimeException("Error: could not query max id in " + table);
1059 }
1060
1061 return id;
1062 }
1063
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001064 static class SqlArguments {
1065 public final String table;
1066 public final String where;
1067 public final String[] args;
1068
1069 SqlArguments(Uri url, String where, String[] args) {
1070 if (url.getPathSegments().size() == 1) {
1071 this.table = url.getPathSegments().get(0);
1072 this.where = where;
1073 this.args = args;
1074 } else if (url.getPathSegments().size() != 2) {
1075 throw new IllegalArgumentException("Invalid URI: " + url);
1076 } else if (!TextUtils.isEmpty(where)) {
1077 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1078 } else {
1079 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001080 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001081 this.args = null;
1082 }
1083 }
1084
1085 SqlArguments(Uri url) {
1086 if (url.getPathSegments().size() == 1) {
1087 table = url.getPathSegments().get(0);
1088 where = null;
1089 args = null;
1090 } else {
1091 throw new IllegalArgumentException("Invalid URI: " + url);
1092 }
1093 }
1094 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001095
1096 private static class ChangeListenerWrapper implements Handler.Callback {
1097
1098 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1099 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1100 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1101
1102 private LauncherProviderChangeListener mListener;
1103
1104 @Override
1105 public boolean handleMessage(Message msg) {
1106 if (mListener != null) {
1107 switch (msg.what) {
1108 case MSG_LAUNCHER_PROVIDER_CHANGED:
1109 mListener.onLauncherProviderChange();
1110 break;
1111 case MSG_EXTRACTED_COLORS_CHANGED:
1112 mListener.onExtractedColorsChanged();
1113 break;
1114 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07001115 Context context = (Context) msg.obj;
1116 if (context != null) {
1117 context.sendBroadcast(new Intent(Launcher.ACTION_APPWIDGET_HOST_RESET)
1118 .setPackage(context.getPackageName()));
1119 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001120 break;
1121 }
1122 }
1123 return true;
1124 }
1125 }
Adam Cohen72960972014-01-15 18:13:55 -08001126}