blob: 49ce06a449ec12299fcf5cfe9f72439cb07733d4 [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;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070049import android.provider.BaseColumns;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050052import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070053
Sunny Goyal0fe505b2014-08-06 09:55:36 -070054import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
55import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070056import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010057import com.android.launcher3.compat.UserHandleCompat;
58import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070060import com.android.launcher3.dynamicui.ExtractionUtils;
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 Goyald3849d12015-10-29 10:28:32 -0700120 }
121 }
122
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 @Override
124 public Cursor query(Uri uri, String[] projection, String selection,
125 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700126 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127
128 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
129 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
130 qb.setTables(args.table);
131
Romain Guy73b979d2009-06-09 12:57:21 -0700132 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
134 result.setNotificationUri(getContext().getContentResolver(), uri);
135
136 return result;
137 }
138
Adam Cohen091440a2015-03-18 14:16:05 -0700139 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500141 if (values == null) {
142 throw new RuntimeException("Error: attempting to insert null values");
143 }
Adam Cohen71483f42014-05-15 14:04:01 -0700144 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 throw new RuntimeException("Error: attempting to add item without specifying an id");
146 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500147 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 return db.insert(table, nullColumnHack, values);
149 }
150
Sunny Goyald1064182015-08-13 12:08:30 -0700151 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700152 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700153 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
154 if (app != null) {
155 app.reloadWorkspace();
156 }
157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700162 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 SqlArguments args = new SqlArguments(uri);
164
Sunny Goyald1064182015-08-13 12:08:30 -0700165 // In very limited cases, we support system|signature permission apps to modify the db.
166 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700167 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700168 return null;
169 }
170 }
171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800175 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700178 notifyListeners();
179
Sunny Goyalc74e4192015-09-08 14:01:03 -0700180 if (Utilities.ATLEAST_MARSHMALLOW) {
181 reloadLauncherIfExternal();
182 } else {
183 // Deprecated behavior to support legacy devices which rely on provider callbacks.
184 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
185 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
186 app.reloadWorkspace();
187 }
188
189 String notify = uri.getQueryParameter("notify");
190 if (notify == null || "true".equals(notify)) {
191 getContext().getContentResolver().notifyChange(uri, null);
192 }
193 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 return uri;
195 }
196
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700197 private boolean initializeExternalAdd(ContentValues values) {
198 // 1. Ensure that externally added items have a valid item id
199 long id = mOpenHelper.generateNewItemId();
200 values.put(LauncherSettings.Favorites._ID, id);
201
202 // 2. In the case of an app widget, and if no app widget id is specified, we
203 // attempt allocate and bind the widget.
204 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
205 if (itemType != null &&
206 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
207 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
208
209 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
210 ComponentName cn = ComponentName.unflattenFromString(
211 values.getAsString(Favorites.APPWIDGET_PROVIDER));
212
213 if (cn != null) {
214 try {
215 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
216 .allocateAppWidgetId();
217 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
218 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
219 return false;
220 }
221 } catch (RuntimeException e) {
222 Log.e(TAG, "Failed to initialize external widget", e);
223 return false;
224 }
225 } else {
226 return false;
227 }
228 }
229
230 // Add screen id if not present
231 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
232 SQLiteStatement stmp = null;
233 try {
234 stmp = mOpenHelper.getWritableDatabase().compileStatement(
235 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
236 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
237 stmp.bindLong(1, screenId);
238
239 ContentValues valuesInserted = new ContentValues();
240 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
241 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
242 return true;
243 } catch (Exception e) {
244 return false;
245 } finally {
246 Utilities.closeSilently(stmp);
247 }
248 }
249
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 @Override
251 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700252 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253 SqlArguments args = new SqlArguments(uri);
254
255 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
256 db.beginTransaction();
257 try {
258 int numValues = values.length;
259 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400260 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700261 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
262 return 0;
263 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 }
265 db.setTransactionSuccessful();
266 } finally {
267 db.endTransaction();
268 }
269
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700270 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700271 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 return values.length;
273 }
274
275 @Override
Yura085c8532014-02-11 15:15:29 +0000276 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
277 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700278 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000279 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
280 db.beginTransaction();
281 try {
282 ContentProviderResult[] result = super.applyBatch(operations);
283 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700284 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000285 return result;
286 } finally {
287 db.endTransaction();
288 }
289 }
290
291 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700293 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
295
296 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
297 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700298 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299
Sunny Goyald1064182015-08-13 12:08:30 -0700300 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 return count;
302 }
303
304 @Override
305 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700306 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
308
Chris Wren1ada10d2013-09-13 18:01:38 -0400309 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
311 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700312 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313
Sunny Goyald1064182015-08-13 12:08:30 -0700314 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 return count;
316 }
317
Sunny Goyal7779d622015-06-11 16:18:39 -0700318 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700319 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700320 if (Binder.getCallingUid() != Process.myUid()) {
321 return null;
322 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700324
325 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700326 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
327 String extractedColors = extras.getString(
328 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
329 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
330 Utilities.getPrefs(getContext()).edit()
331 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
332 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
333 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700334 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700335 Bundle result = new Bundle();
336 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
337 return result;
338 }
Sunny Goyald2497482015-09-22 18:24:19 -0700339 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
340 clearFlagEmptyDbCreated();
341 return null;
342 }
343 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
344 Bundle result = new Bundle();
345 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
346 return result;
347 }
348 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
349 Bundle result = new Bundle();
350 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
351 return result;
352 }
353 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
354 Bundle result = new Bundle();
355 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
356 return result;
357 }
358 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
359 createEmptyDB();
360 return null;
361 }
362 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
363 loadDefaultFavoritesIfNecessary();
364 return null;
365 }
Sunny Goyald2497482015-09-22 18:24:19 -0700366 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
367 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
368 return null;
369 }
370 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
371 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
372 return null;
373 }
374 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800375 // Are you sure? (y/n)
376 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700377 return null;
378 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700379 }
380 return null;
381 }
382
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700383 /**
384 * Deletes any empty folder from the DB.
385 * @return Ids of deleted folders.
386 */
Sunny Goyald2497482015-09-22 18:24:19 -0700387 private ArrayList<Long> deleteEmptyFolders() {
388 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700389 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
390 db.beginTransaction();
391 try {
392 // Select folders whose id do not match any container value.
393 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
394 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
395 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
396 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700397 + Favorites.TABLE_NAME + ")";
398 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700399 new String[] {LauncherSettings.Favorites._ID},
400 selection, null, null, null, null);
401 while (c.moveToNext()) {
402 folderIds.add(c.getLong(0));
403 }
404 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700405 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700406 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700407 LauncherSettings.Favorites._ID, folderIds), null);
408 }
409 db.setTransactionSuccessful();
410 } catch (SQLException ex) {
411 Log.e(TAG, ex.getMessage(), ex);
412 folderIds.clear();
413 } finally {
414 db.endTransaction();
415 }
416 return folderIds;
417 }
418
Sunny Goyalf076eae2016-01-11 12:25:10 -0800419 /**
420 * Overridden in tests
421 */
422 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400423 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400424 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700425 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400426 }
427
Adam Cohen091440a2015-03-18 14:16:05 -0700428 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400429 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800430 }
431
Brian Muramatsu5524b492012-10-02 16:55:54 -0700432 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700433 * Clears all the data for a fresh start.
434 */
Sunny Goyald2497482015-09-22 18:24:19 -0700435 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700436 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
437 }
438
Sunny Goyald2497482015-09-22 18:24:19 -0700439 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700440 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700441 }
442
Sunny Goyal42de82f2014-09-26 22:09:29 -0700443 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700444 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700445 * 1) From the app restrictions
446 * 2) From a package provided by play store
447 * 3) From a partner configuration APK, already in the system image
448 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700449 */
Sunny Goyald2497482015-09-22 18:24:19 -0700450 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700451 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700452
Winson Chungc763c4e2013-07-19 13:49:06 -0700453 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500454 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200455
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700456 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
457 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700458 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700459 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700460 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700461 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700462 final Partner partner = Partner.get(getContext().getPackageManager());
463 if (partner != null && partner.hasDefaultLayout()) {
464 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700465 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700466 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700468 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700469 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700470 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700471 }
472 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473
Sunny Goyal9d219682014-10-23 14:21:02 -0700474 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700475 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700477 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800478
479 // There might be some partially restored DB items, due to buggy restore logic in
480 // previous versions of launcher.
481 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700482 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700483 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
484 && usingExternallyProvidedLayout) {
485 // Unable to load external layout. Cleanup and load the internal layout.
486 createEmptyDB();
487 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700489 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700490 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700491 }
492 }
493
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700494 /**
495 * Creates workspace loader from an XML resource listed in the app restrictions.
496 *
497 * @return the loader if the restrictions are set and the resource exists; null otherwise.
498 */
499 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700500 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700501 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700502 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 return null;
504 }
505
506 Context ctx = getContext();
507 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
508 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700509 if (bundle == null) {
510 return null;
511 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512
Sunny Goyal35ca8732015-04-06 10:45:31 -0700513 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700514 if (packageName != null) {
515 try {
516 Resources targetResources = ctx.getPackageManager()
517 .getResourcesForApplication(packageName);
518 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 } catch (NameNotFoundException e) {
521 Log.e(TAG, "Target package for restricted profile not found", e);
522 return null;
523 }
524 }
525 return null;
526 }
527
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700528 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700529 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700530 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700531 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700532 mOpenHelper, getContext().getResources(), defaultLayout);
533 }
534
Sunny Goyald3849d12015-10-29 10:28:32 -0700535 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800536 * The class is subclassed in tests to create an in-memory db.
537 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700538 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700539 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700541 private long mMaxItemId = -1;
542 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800543
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700544 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
545 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700546 // Table creation sometimes fails silently, which leads to a crash loop.
547 // This way, we will try to create a table every time after crash, so the device
548 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700549 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700550 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
551 // This operation is a no-op if the table already exists.
552 addFavoritesTable(getWritableDatabase(), true);
553 addWorkspacesTable(getWritableDatabase(), true);
554 }
555
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700556 initIds();
557 }
558
559 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700560 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700561 */
562 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700563 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700564 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
565 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700566 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700567 }
568
569 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700570 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
571 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700572 if (mMaxItemId == -1) {
573 mMaxItemId = initializeMaxItemId(getWritableDatabase());
574 }
575 if (mMaxScreenId == -1) {
576 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700577 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 }
579
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700580 private boolean tableExists(String tableName) {
581 Cursor c = getReadableDatabase().query(
582 true, "sqlite_master", new String[] {"tbl_name"},
583 "tbl_name = ?", new String[] {tableName},
584 null, null, null, null, null);
585 try {
586 return c.getCount() > 0;
587 } finally {
588 c.close();
589 }
590 }
591
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800592 @Override
593 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800594 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700595
Adam Cohendcd297f2013-06-18 13:13:40 -0700596 mMaxItemId = 1;
597 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700598
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700599 addFavoritesTable(db, false);
600 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800602 // Fresh and clean launcher DB.
603 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800604 onEmptyDbCreated();
605 }
606
607 /**
608 * Overriden in tests.
609 */
610 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700611 // Database was just created, so wipe any previous widgets
612 if (mWidgetHostResetHandler != null) {
613 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyalda4fe1a2016-05-26 16:05:17 -0700614 mWidgetHostResetHandler.sendMessage(Message.obtain(
615 mWidgetHostResetHandler,
616 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET,
617 mContext
618 ));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700619 }
620
Sunny Goyalf076eae2016-01-11 12:25:10 -0800621 // Set the flag for empty DB
622 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700623
624 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800625 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
626 mContext);
627 }
628
629 protected long getDefaultUserSerial() {
630 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
631 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632 }
633
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700634 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700635 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700636 }
637
638 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
639 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700640 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800641 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400642 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
643 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700644 ");");
645 }
646
Adam Cohen119285e2014-04-02 16:59:08 -0700647 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700648 // Delete items directly on the workspace who's screen id doesn't exist
649 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
650 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700651 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700652 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700653 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700654 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700655 " AND " +
656 LauncherSettings.Favorites.CONTAINER + " = " +
657 LauncherSettings.Favorites.CONTAINER_DESKTOP;
658 db.execSQL(removeOrphanedDesktopItems);
659
660 // Delete items contained in folders which no longer exist (after above statement)
661 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
662 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700663 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700664 " WHERE " +
665 LauncherSettings.Favorites.CONTAINER + " <> " +
666 LauncherSettings.Favorites.CONTAINER_DESKTOP +
667 " AND "
668 + LauncherSettings.Favorites.CONTAINER + " <> " +
669 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
670 " AND "
671 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700672 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
674 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
675 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700676 }
677
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 @Override
679 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700680 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 switch (oldVersion) {
682 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800683 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800684 case 12: {
685 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
686 // to persist workspace screens and their relative order.
687 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700688 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 }
690 case 13: {
691 db.beginTransaction();
692 try {
693 // Insert new column for holding widget provider name
694 db.execSQL("ALTER TABLE favorites " +
695 "ADD COLUMN appWidgetProvider TEXT;");
696 db.setTransactionSuccessful();
697 } catch (SQLException ex) {
698 Log.e(TAG, ex.getMessage(), ex);
699 // Old version remains, which means we wipe old data
700 break;
701 } finally {
702 db.endTransaction();
703 }
704 }
705 case 14: {
706 db.beginTransaction();
707 try {
708 // Insert new column for holding update timestamp
709 db.execSQL("ALTER TABLE favorites " +
710 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
711 db.execSQL("ALTER TABLE workspaceScreens " +
712 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
713 db.setTransactionSuccessful();
714 } catch (SQLException ex) {
715 Log.e(TAG, ex.getMessage(), ex);
716 // Old version remains, which means we wipe old data
717 break;
718 } finally {
719 db.endTransaction();
720 }
721 }
722 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700723 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800724 // Old version remains, which means we wipe old data
725 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800726 }
727 }
728 case 16: {
729 // We use the db version upgrade here to identify users who may not have seen
730 // clings yet (because they weren't available), but for whom the clings are now
731 // available (tablet users). Because one of the possible cling flows (migration)
732 // is very destructive (wipes out workspaces), we want to prevent this from showing
733 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800734 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 }
736 case 17: {
737 // No-op
738 }
739 case 18: {
740 // Due to a data loss bug, some users may have items associated with screen ids
741 // which no longer exist. Since this can cause other problems, and since the user
742 // will never see these items anyway, we use database upgrade as an opportunity to
743 // clean things up.
744 removeOrphanedItems(db);
745 }
746 case 19: {
747 // Add userId column
748 if (!addProfileColumn(db)) {
749 // Old version remains, which means we wipe old data
750 break;
751 }
752 }
753 case 20:
754 if (!updateFolderItemsRank(db, true)) {
755 break;
756 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800757 case 21:
758 // Recreate workspace table with screen id a primary key
759 if (!recreateWorkspaceTable(db)) {
760 break;
761 }
762 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700763 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
764 // Old version remains, which means we wipe old data
765 break;
766 }
767 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700768 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700769 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700770 case 24:
771 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700772 case 25:
773 convertShortcutsToLauncherActivities(db);
774 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800775 // DB Upgraded successfully
776 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400777 }
778 }
779
Sunny Goyala2cc6242015-01-14 14:23:02 -0800780 // DB was not upgraded
781 Log.w(TAG, "Destroying all old data.");
782 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800783 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800784
Adam Cohen9b1d0622014-05-21 19:01:57 -0700785 @Override
786 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
787 // This shouldn't happen -- throw our hands up in the air and start over.
788 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
789 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700790 createEmptyDB(db);
791 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700792
Sunny Goyal42de82f2014-09-26 22:09:29 -0700793 /**
794 * Clears all the data for a fresh start.
795 */
796 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700797 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
798 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700799 onCreate(db);
800 }
801
Sunny Goyald2f38192015-02-25 10:46:34 -0800802 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700803 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
804 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
805 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700806 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700807 db.beginTransaction();
808 Cursor c = null;
809 SQLiteStatement updateStmt = null;
810
811 try {
812 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700813 long userSerial = getDefaultUserSerial();
814 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700815 Favorites._ID,
816 Favorites.INTENT,
817 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
818 null, null, null, null);
819
820 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
821 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
822
823 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
824 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
825
826 while (c.moveToNext()) {
827 String intentDescription = c.getString(intentIndex);
828 Intent intent;
829 try {
830 intent = Intent.parseUri(intentDescription, 0);
831 } catch (URISyntaxException e) {
832 Log.e(TAG, "Unable to parse intent", e);
833 continue;
834 }
835
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700836 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700837 continue;
838 }
839
840 long id = c.getLong(idIndex);
841 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700842 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 }
844 db.setTransactionSuccessful();
845 } catch (SQLException ex) {
846 Log.w(TAG, "Error deduping shortcuts", ex);
847 } finally {
848 db.endTransaction();
849 if (c != null) {
850 c.close();
851 }
852 if (updateStmt != null) {
853 updateStmt.close();
854 }
855 }
856 }
857
858 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800859 * Recreates workspace table and migrates data to the new table.
860 */
861 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
862 db.beginTransaction();
863 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700864 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800865 new String[] {LauncherSettings.WorkspaceScreens._ID},
866 null, null, null, null,
867 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
868 ArrayList<Long> sortedIDs = new ArrayList<Long>();
869 long maxId = 0;
870 try {
871 while (c.moveToNext()) {
872 Long id = c.getLong(0);
873 if (!sortedIDs.contains(id)) {
874 sortedIDs.add(id);
875 maxId = Math.max(maxId, id);
876 }
877 }
878 } finally {
879 c.close();
880 }
881
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700882 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700883 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800884
885 // Add all screen ids back
886 int total = sortedIDs.size();
887 for (int i = 0; i < total; i++) {
888 ContentValues values = new ContentValues();
889 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
890 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
891 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700892 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800893 }
894 db.setTransactionSuccessful();
895 mMaxScreenId = maxId;
896 } catch (SQLException ex) {
897 // Old version remains, which means we wipe old data
898 Log.e(TAG, ex.getMessage(), ex);
899 return false;
900 } finally {
901 db.endTransaction();
902 }
903 return true;
904 }
905
Adam Cohen091440a2015-03-18 14:16:05 -0700906 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800907 db.beginTransaction();
908 try {
909 if (addRankColumn) {
910 // Insert new column for holding rank
911 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
912 }
913
914 // Get a map for folder ID to folder width
915 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
916 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
917 + " GROUP BY container;",
918 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
919
920 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800921 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
922 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800923 new Object[] {c.getLong(1) + 1, c.getLong(0)});
924 }
925
926 c.close();
927 db.setTransactionSuccessful();
928 } catch (SQLException ex) {
929 // Old version remains, which means we wipe old data
930 Log.e(TAG, ex.getMessage(), ex);
931 return false;
932 } finally {
933 db.endTransaction();
934 }
935 return true;
936 }
937
Kenny Guyed131872014-04-30 03:02:21 +0100938 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700939 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700940 }
941
942 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100943 db.beginTransaction();
944 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700945 db.execSQL("ALTER TABLE favorites ADD COLUMN "
946 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100947 db.setTransactionSuccessful();
948 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100949 Log.e(TAG, ex.getMessage(), ex);
950 return false;
951 } finally {
952 db.endTransaction();
953 }
954 return true;
955 }
956
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700957 // Generates a new ID to use for an object in your database. This method should be only
958 // called from the main UI thread. As an exception, we do call it when we call the
959 // constructor from the worker thread; however, this doesn't extend until after the
960 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
961 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700962 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700963 public long generateNewItemId() {
964 if (mMaxItemId < 0) {
965 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700966 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700967 mMaxItemId += 1;
968 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700969 }
970
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700971 @Override
972 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700973 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700974 }
975
Chris Wren5dee7af2013-12-20 17:22:11 -0500976 public void checkId(String table, ContentValues values) {
977 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700978 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500979 mMaxScreenId = Math.max(id, mMaxScreenId);
980 } else {
981 mMaxItemId = Math.max(id, mMaxItemId);
982 }
983 }
984
Adam Cohendcd297f2013-06-18 13:13:40 -0700985 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700986 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700987 }
988
989 // Generates a new ID to use for an workspace screen in your database. This method
990 // should be only called from the main UI thread. As an exception, we do call it when we
991 // call the constructor from the worker thread; however, this doesn't extend until after the
992 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
993 // after that point
994 public long generateNewScreenId() {
995 if (mMaxScreenId < 0) {
996 throw new RuntimeException("Error: max screen id was not initialized");
997 }
998 mMaxScreenId += 1;
999 return mMaxScreenId;
1000 }
1001
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001003 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001004 }
1005
Adam Cohen091440a2015-03-18 14:16:05 -07001006 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001007 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001008 // TODO: Use multiple loaders with fall-back and transaction.
1009 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001010
1011 // Add the screens specified by the items above
1012 Collections.sort(screenIds);
1013 int rank = 0;
1014 ContentValues values = new ContentValues();
1015 for (Long id : screenIds) {
1016 values.clear();
1017 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1018 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001019 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001020 throw new RuntimeException("Failed initialize screen table"
1021 + "from default layout");
1022 }
1023 rank++;
1024 }
1025
1026 // Ensure that the max ids are initialized
1027 mMaxItemId = initializeMaxItemId(db);
1028 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001029
Adam Cohen71483f42014-05-15 14:04:01 -07001030 return count;
1031 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001032 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001033
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001034 /**
1035 * @return the max _id in the provided table.
1036 */
Adam Cohen091440a2015-03-18 14:16:05 -07001037 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001038 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1039 // get the result
1040 long id = -1;
1041 if (c != null && c.moveToNext()) {
1042 id = c.getLong(0);
1043 }
1044 if (c != null) {
1045 c.close();
1046 }
1047
1048 if (id == -1) {
1049 throw new RuntimeException("Error: could not query max id in " + table);
1050 }
1051
1052 return id;
1053 }
1054
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001055 static class SqlArguments {
1056 public final String table;
1057 public final String where;
1058 public final String[] args;
1059
1060 SqlArguments(Uri url, String where, String[] args) {
1061 if (url.getPathSegments().size() == 1) {
1062 this.table = url.getPathSegments().get(0);
1063 this.where = where;
1064 this.args = args;
1065 } else if (url.getPathSegments().size() != 2) {
1066 throw new IllegalArgumentException("Invalid URI: " + url);
1067 } else if (!TextUtils.isEmpty(where)) {
1068 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1069 } else {
1070 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001071 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001072 this.args = null;
1073 }
1074 }
1075
1076 SqlArguments(Uri url) {
1077 if (url.getPathSegments().size() == 1) {
1078 table = url.getPathSegments().get(0);
1079 where = null;
1080 args = null;
1081 } else {
1082 throw new IllegalArgumentException("Invalid URI: " + url);
1083 }
1084 }
1085 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001086
1087 private static class ChangeListenerWrapper implements Handler.Callback {
1088
1089 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1090 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1091 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1092
1093 private LauncherProviderChangeListener mListener;
1094
1095 @Override
1096 public boolean handleMessage(Message msg) {
1097 if (mListener != null) {
1098 switch (msg.what) {
1099 case MSG_LAUNCHER_PROVIDER_CHANGED:
1100 mListener.onLauncherProviderChange();
1101 break;
1102 case MSG_EXTRACTED_COLORS_CHANGED:
1103 mListener.onExtractedColorsChanged();
1104 break;
1105 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07001106 Context context = (Context) msg.obj;
1107 if (context != null) {
1108 context.sendBroadcast(new Intent(Launcher.ACTION_APPWIDGET_HOST_RESET)
1109 .setPackage(context.getPackageName()));
1110 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001111 break;
1112 }
1113 }
1114 return true;
1115 }
1116 }
Adam Cohen72960972014-01-15 18:13:55 -08001117}