blob: 4e7d57bb2913692715cb130147aea7bfd17ae49f [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
35import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteOpenHelper;
38import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070042import android.os.Build;
43import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070050
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
52import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070053import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070056import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040057import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070058import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070059import com.android.launcher3.provider.LauncherDbUtils;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070071 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080072 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070074 private static final int DATABASE_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Sunny Goyale5bb7052015-07-27 14:36:07 -070076 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070077
Sunny Goyale87e6ab2014-11-21 22:42:53 -080078 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070080 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
81
Sunny Goyalb5b55c82016-05-10 12:28:59 -070082 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
83 private Handler mListenerHandler;
84
Sunny Goyalf076eae2016-01-11 12:25:10 -080085 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
87 @Override
88 public boolean onCreate() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -070089 mListenerHandler = new Handler(mListenerWrapper);
90
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 return true;
93 }
94
Sunny Goyald3849d12015-10-29 10:28:32 -070095 /**
96 * Sets a provider listener.
97 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -070099 Preconditions.assertUIThread();
100 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public String getType(Uri uri) {
105 SqlArguments args = new SqlArguments(uri, null, null);
106 if (TextUtils.isEmpty(args.where)) {
107 return "vnd.android.cursor.dir/" + args.table;
108 } else {
109 return "vnd.android.cursor.item/" + args.table;
110 }
111 }
112
Sunny Goyalf076eae2016-01-11 12:25:10 -0800113 /**
114 * Overridden in tests
115 */
116 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700117 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700118 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700119
120 if (RestoreDbTask.isPending(getContext())) {
121 if (!RestoreDbTask.performRestore(mOpenHelper)) {
122 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
123 }
124 // Set is pending to false irrespective of the result, so that it doesn't get
125 // executed again.
126 RestoreDbTask.setPending(getContext(), false);
127 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700128 }
129 }
130
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131 @Override
132 public Cursor query(Uri uri, String[] projection, String selection,
133 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700134 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800135
136 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
137 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
138 qb.setTables(args.table);
139
Romain Guy73b979d2009-06-09 12:57:21 -0700140 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
142 result.setNotificationUri(getContext().getContentResolver(), uri);
143
144 return result;
145 }
146
Adam Cohen091440a2015-03-18 14:16:05 -0700147 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500149 if (values == null) {
150 throw new RuntimeException("Error: attempting to insert null values");
151 }
Adam Cohen71483f42014-05-15 14:04:01 -0700152 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153 throw new RuntimeException("Error: attempting to add item without specifying an id");
154 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500155 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156 return db.insert(table, nullColumnHack, values);
157 }
158
Sunny Goyald1064182015-08-13 12:08:30 -0700159 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700160 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700161 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
162 if (app != null) {
163 app.reloadWorkspace();
164 }
165 }
166 }
167
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168 @Override
169 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700170 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171 SqlArguments args = new SqlArguments(uri);
172
Sunny Goyald1064182015-08-13 12:08:30 -0700173 // In very limited cases, we support system|signature permission apps to modify the db.
174 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700175 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700176 return null;
177 }
178 }
179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400181 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800183 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
185 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700186 notifyListeners();
187
Sunny Goyalc74e4192015-09-08 14:01:03 -0700188 if (Utilities.ATLEAST_MARSHMALLOW) {
189 reloadLauncherIfExternal();
190 } else {
191 // Deprecated behavior to support legacy devices which rely on provider callbacks.
192 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
193 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
194 app.reloadWorkspace();
195 }
196
197 String notify = uri.getQueryParameter("notify");
198 if (notify == null || "true".equals(notify)) {
199 getContext().getContentResolver().notifyChange(uri, null);
200 }
201 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 return uri;
203 }
204
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700205 private boolean initializeExternalAdd(ContentValues values) {
206 // 1. Ensure that externally added items have a valid item id
207 long id = mOpenHelper.generateNewItemId();
208 values.put(LauncherSettings.Favorites._ID, id);
209
210 // 2. In the case of an app widget, and if no app widget id is specified, we
211 // attempt allocate and bind the widget.
212 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
213 if (itemType != null &&
214 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
215 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
216
217 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
218 ComponentName cn = ComponentName.unflattenFromString(
219 values.getAsString(Favorites.APPWIDGET_PROVIDER));
220
221 if (cn != null) {
222 try {
223 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
224 .allocateAppWidgetId();
225 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
226 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
227 return false;
228 }
229 } catch (RuntimeException e) {
230 Log.e(TAG, "Failed to initialize external widget", e);
231 return false;
232 }
233 } else {
234 return false;
235 }
236 }
237
238 // Add screen id if not present
239 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
240 SQLiteStatement stmp = null;
241 try {
242 stmp = mOpenHelper.getWritableDatabase().compileStatement(
243 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
244 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
245 stmp.bindLong(1, screenId);
246
247 ContentValues valuesInserted = new ContentValues();
248 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
249 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
250 return true;
251 } catch (Exception e) {
252 return false;
253 } finally {
254 Utilities.closeSilently(stmp);
255 }
256 }
257
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800258 @Override
259 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700260 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800261 SqlArguments args = new SqlArguments(uri);
262
263 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
264 db.beginTransaction();
265 try {
266 int numValues = values.length;
267 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400268 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700269 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
270 return 0;
271 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 }
273 db.setTransactionSuccessful();
274 } finally {
275 db.endTransaction();
276 }
277
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700278 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700279 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800280 return values.length;
281 }
282
283 @Override
Yura085c8532014-02-11 15:15:29 +0000284 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
285 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700286 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000287 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
288 db.beginTransaction();
289 try {
290 ContentProviderResult[] result = super.applyBatch(operations);
291 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700292 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000293 return result;
294 } finally {
295 db.endTransaction();
296 }
297 }
298
299 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700301 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
303
304 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
305 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700306 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307
Sunny Goyald1064182015-08-13 12:08:30 -0700308 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800309 return count;
310 }
311
312 @Override
313 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700314 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
316
Chris Wren1ada10d2013-09-13 18:01:38 -0400317 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
319 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700320 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800321
Sunny Goyald1064182015-08-13 12:08:30 -0700322 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800323 return count;
324 }
325
Sunny Goyal7779d622015-06-11 16:18:39 -0700326 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700327 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700328 if (Binder.getCallingUid() != Process.myUid()) {
329 return null;
330 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700331 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700332
333 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700334 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
335 String extractedColors = extras.getString(
336 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
337 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
338 Utilities.getPrefs(getContext()).edit()
339 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
340 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
341 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700342 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700343 Bundle result = new Bundle();
344 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
345 return result;
346 }
Sunny Goyald2497482015-09-22 18:24:19 -0700347 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
348 clearFlagEmptyDbCreated();
349 return null;
350 }
351 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
352 Bundle result = new Bundle();
353 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
354 return result;
355 }
356 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
357 Bundle result = new Bundle();
358 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
359 return result;
360 }
361 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
362 Bundle result = new Bundle();
363 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
364 return result;
365 }
366 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
367 createEmptyDB();
368 return null;
369 }
370 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
371 loadDefaultFavoritesIfNecessary();
372 return null;
373 }
Sunny Goyald2497482015-09-22 18:24:19 -0700374 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
375 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
376 return null;
377 }
378 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
379 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
380 return null;
381 }
382 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800383 // Are you sure? (y/n)
384 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700385 return null;
386 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700387 }
388 return null;
389 }
390
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700391 /**
392 * Deletes any empty folder from the DB.
393 * @return Ids of deleted folders.
394 */
Sunny Goyald2497482015-09-22 18:24:19 -0700395 private ArrayList<Long> deleteEmptyFolders() {
396 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700397 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
398 db.beginTransaction();
399 try {
400 // Select folders whose id do not match any container value.
401 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
402 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
403 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
404 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700405 + Favorites.TABLE_NAME + ")";
406 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700407 new String[] {LauncherSettings.Favorites._ID},
408 selection, null, null, null, null);
409 while (c.moveToNext()) {
410 folderIds.add(c.getLong(0));
411 }
412 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700413 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700414 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700415 LauncherSettings.Favorites._ID, folderIds), null);
416 }
417 db.setTransactionSuccessful();
418 } catch (SQLException ex) {
419 Log.e(TAG, ex.getMessage(), ex);
420 folderIds.clear();
421 } finally {
422 db.endTransaction();
423 }
424 return folderIds;
425 }
426
Sunny Goyalf076eae2016-01-11 12:25:10 -0800427 /**
428 * Overridden in tests
429 */
430 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400431 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400432 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700433 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400434 }
435
Adam Cohen091440a2015-03-18 14:16:05 -0700436 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438 }
439
Brian Muramatsu5524b492012-10-02 16:55:54 -0700440 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700441 * Clears all the data for a fresh start.
442 */
Sunny Goyald2497482015-09-22 18:24:19 -0700443 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700444 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
445 }
446
Sunny Goyald2497482015-09-22 18:24:19 -0700447 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700448 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700449 }
450
Sunny Goyal42de82f2014-09-26 22:09:29 -0700451 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700452 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700453 * 1) From the app restrictions
454 * 2) From a package provided by play store
455 * 3) From a partner configuration APK, already in the system image
456 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700457 */
Sunny Goyald2497482015-09-22 18:24:19 -0700458 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700459 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700460
Winson Chungc763c4e2013-07-19 13:49:06 -0700461 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500462 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200463
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700464 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
465 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700466 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700467 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700468 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700469 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700470 final Partner partner = Partner.get(getContext().getPackageManager());
471 if (partner != null && partner.hasDefaultLayout()) {
472 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700473 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700474 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700475 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700477 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700478 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700479 }
480 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481
Sunny Goyal9d219682014-10-23 14:21:02 -0700482 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700483 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700484 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700485 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800486
487 // There might be some partially restored DB items, due to buggy restore logic in
488 // previous versions of launcher.
489 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700490 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700491 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
492 && usingExternallyProvidedLayout) {
493 // Unable to load external layout. Cleanup and load the internal layout.
494 createEmptyDB();
495 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700496 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700497 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700498 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700499 }
500 }
501
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700502 /**
503 * Creates workspace loader from an XML resource listed in the app restrictions.
504 *
505 * @return the loader if the restrictions are set and the resource exists; null otherwise.
506 */
507 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700508 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700509 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700510 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700511 return null;
512 }
513
514 Context ctx = getContext();
515 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
516 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700517 if (bundle == null) {
518 return null;
519 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520
Sunny Goyal35ca8732015-04-06 10:45:31 -0700521 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700522 if (packageName != null) {
523 try {
524 Resources targetResources = ctx.getPackageManager()
525 .getResourcesForApplication(packageName);
526 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700527 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700528 } catch (NameNotFoundException e) {
529 Log.e(TAG, "Target package for restricted profile not found", e);
530 return null;
531 }
532 }
533 return null;
534 }
535
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700536 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700537 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700538 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700539 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700540 mOpenHelper, getContext().getResources(), defaultLayout);
541 }
542
Sunny Goyald3849d12015-10-29 10:28:32 -0700543 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800544 * The class is subclassed in tests to create an in-memory db.
545 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700546 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700547 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700549 private long mMaxItemId = -1;
550 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700552 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
553 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700554 // Table creation sometimes fails silently, which leads to a crash loop.
555 // This way, we will try to create a table every time after crash, so the device
556 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700558 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
559 // This operation is a no-op if the table already exists.
560 addFavoritesTable(getWritableDatabase(), true);
561 addWorkspacesTable(getWritableDatabase(), true);
562 }
563
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700564 initIds();
565 }
566
567 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700568 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700569 */
570 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700571 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
573 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700574 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700575 }
576
577 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700578 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
579 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700580 if (mMaxItemId == -1) {
581 mMaxItemId = initializeMaxItemId(getWritableDatabase());
582 }
583 if (mMaxScreenId == -1) {
584 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700585 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800586 }
587
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700588 private boolean tableExists(String tableName) {
589 Cursor c = getReadableDatabase().query(
590 true, "sqlite_master", new String[] {"tbl_name"},
591 "tbl_name = ?", new String[] {tableName},
592 null, null, null, null, null);
593 try {
594 return c.getCount() > 0;
595 } finally {
596 c.close();
597 }
598 }
599
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800600 @Override
601 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800602 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700603
Adam Cohendcd297f2013-06-18 13:13:40 -0700604 mMaxItemId = 1;
605 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700606
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700607 addFavoritesTable(db, false);
608 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800610 // Fresh and clean launcher DB.
611 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800612 onEmptyDbCreated();
613 }
614
615 /**
616 * Overriden in tests.
617 */
618 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700619 // Database was just created, so wipe any previous widgets
620 if (mWidgetHostResetHandler != null) {
621 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyalda4fe1a2016-05-26 16:05:17 -0700622 mWidgetHostResetHandler.sendMessage(Message.obtain(
623 mWidgetHostResetHandler,
624 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET,
625 mContext
626 ));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700627 }
628
Sunny Goyalf076eae2016-01-11 12:25:10 -0800629 // Set the flag for empty DB
630 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700631
632 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
634 mContext);
635 }
636
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700637 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800638 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
639 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 }
641
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700642 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700643 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700644 }
645
646 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
647 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700648 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800649 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400650 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
651 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700652 ");");
653 }
654
Adam Cohen119285e2014-04-02 16:59:08 -0700655 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700656 // Delete items directly on the workspace who's screen id doesn't exist
657 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
658 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700659 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700660 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700661 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700662 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700663 " AND " +
664 LauncherSettings.Favorites.CONTAINER + " = " +
665 LauncherSettings.Favorites.CONTAINER_DESKTOP;
666 db.execSQL(removeOrphanedDesktopItems);
667
668 // Delete items contained in folders which no longer exist (after above statement)
669 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
670 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700671 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700672 " WHERE " +
673 LauncherSettings.Favorites.CONTAINER + " <> " +
674 LauncherSettings.Favorites.CONTAINER_DESKTOP +
675 " AND "
676 + LauncherSettings.Favorites.CONTAINER + " <> " +
677 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
678 " AND "
679 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700680 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700681 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
682 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
683 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700684 }
685
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 @Override
687 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700688 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 switch (oldVersion) {
690 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800691 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800692 case 12: {
693 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
694 // to persist workspace screens and their relative order.
695 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700696 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 }
698 case 13: {
699 db.beginTransaction();
700 try {
701 // Insert new column for holding widget provider name
702 db.execSQL("ALTER TABLE favorites " +
703 "ADD COLUMN appWidgetProvider TEXT;");
704 db.setTransactionSuccessful();
705 } catch (SQLException ex) {
706 Log.e(TAG, ex.getMessage(), ex);
707 // Old version remains, which means we wipe old data
708 break;
709 } finally {
710 db.endTransaction();
711 }
712 }
713 case 14: {
714 db.beginTransaction();
715 try {
716 // Insert new column for holding update timestamp
717 db.execSQL("ALTER TABLE favorites " +
718 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
719 db.execSQL("ALTER TABLE workspaceScreens " +
720 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
721 db.setTransactionSuccessful();
722 } catch (SQLException ex) {
723 Log.e(TAG, ex.getMessage(), ex);
724 // Old version remains, which means we wipe old data
725 break;
726 } finally {
727 db.endTransaction();
728 }
729 }
730 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700731 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 // Old version remains, which means we wipe old data
733 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800734 }
735 }
736 case 16: {
737 // We use the db version upgrade here to identify users who may not have seen
738 // clings yet (because they weren't available), but for whom the clings are now
739 // available (tablet users). Because one of the possible cling flows (migration)
740 // is very destructive (wipes out workspaces), we want to prevent this from showing
741 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800742 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 }
744 case 17: {
745 // No-op
746 }
747 case 18: {
748 // Due to a data loss bug, some users may have items associated with screen ids
749 // which no longer exist. Since this can cause other problems, and since the user
750 // will never see these items anyway, we use database upgrade as an opportunity to
751 // clean things up.
752 removeOrphanedItems(db);
753 }
754 case 19: {
755 // Add userId column
756 if (!addProfileColumn(db)) {
757 // Old version remains, which means we wipe old data
758 break;
759 }
760 }
761 case 20:
762 if (!updateFolderItemsRank(db, true)) {
763 break;
764 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800765 case 21:
766 // Recreate workspace table with screen id a primary key
767 if (!recreateWorkspaceTable(db)) {
768 break;
769 }
770 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700771 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
772 // Old version remains, which means we wipe old data
773 break;
774 }
775 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700776 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700777 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700778 case 24:
779 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700780 case 25:
781 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700782 case 26:
783 // QSB was moved to the grid. Clear the first row on screen 0.
784 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
785 !LauncherDbUtils.prepareScreenZeroToHostQsb(db)) {
786 break;
787 }
788 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 // DB Upgraded successfully
790 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400791 }
792 }
793
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 // DB was not upgraded
795 Log.w(TAG, "Destroying all old data.");
796 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800797 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800798
Adam Cohen9b1d0622014-05-21 19:01:57 -0700799 @Override
800 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
801 // This shouldn't happen -- throw our hands up in the air and start over.
802 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
803 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700804 createEmptyDB(db);
805 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700806
Sunny Goyal42de82f2014-09-26 22:09:29 -0700807 /**
808 * Clears all the data for a fresh start.
809 */
810 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700811 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
812 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700813 onCreate(db);
814 }
815
Sunny Goyald2f38192015-02-25 10:46:34 -0800816 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700817 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
818 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
819 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700820 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700821 db.beginTransaction();
822 Cursor c = null;
823 SQLiteStatement updateStmt = null;
824
825 try {
826 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700827 long userSerial = getDefaultUserSerial();
828 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700829 Favorites._ID,
830 Favorites.INTENT,
831 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
832 null, null, null, null);
833
834 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
835 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
836
837 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
838 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
839
840 while (c.moveToNext()) {
841 String intentDescription = c.getString(intentIndex);
842 Intent intent;
843 try {
844 intent = Intent.parseUri(intentDescription, 0);
845 } catch (URISyntaxException e) {
846 Log.e(TAG, "Unable to parse intent", e);
847 continue;
848 }
849
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700850 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700851 continue;
852 }
853
854 long id = c.getLong(idIndex);
855 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700856 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700857 }
858 db.setTransactionSuccessful();
859 } catch (SQLException ex) {
860 Log.w(TAG, "Error deduping shortcuts", ex);
861 } finally {
862 db.endTransaction();
863 if (c != null) {
864 c.close();
865 }
866 if (updateStmt != null) {
867 updateStmt.close();
868 }
869 }
870 }
871
872 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800873 * Recreates workspace table and migrates data to the new table.
874 */
875 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
876 db.beginTransaction();
877 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700878 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800879 new String[] {LauncherSettings.WorkspaceScreens._ID},
880 null, null, null, null,
881 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
882 ArrayList<Long> sortedIDs = new ArrayList<Long>();
883 long maxId = 0;
884 try {
885 while (c.moveToNext()) {
886 Long id = c.getLong(0);
887 if (!sortedIDs.contains(id)) {
888 sortedIDs.add(id);
889 maxId = Math.max(maxId, id);
890 }
891 }
892 } finally {
893 c.close();
894 }
895
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700896 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700897 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800898
899 // Add all screen ids back
900 int total = sortedIDs.size();
901 for (int i = 0; i < total; i++) {
902 ContentValues values = new ContentValues();
903 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
904 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
905 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700906 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800907 }
908 db.setTransactionSuccessful();
909 mMaxScreenId = maxId;
910 } catch (SQLException ex) {
911 // Old version remains, which means we wipe old data
912 Log.e(TAG, ex.getMessage(), ex);
913 return false;
914 } finally {
915 db.endTransaction();
916 }
917 return true;
918 }
919
Adam Cohen091440a2015-03-18 14:16:05 -0700920 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800921 db.beginTransaction();
922 try {
923 if (addRankColumn) {
924 // Insert new column for holding rank
925 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
926 }
927
928 // Get a map for folder ID to folder width
929 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
930 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
931 + " GROUP BY container;",
932 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
933
934 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800935 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
936 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800937 new Object[] {c.getLong(1) + 1, c.getLong(0)});
938 }
939
940 c.close();
941 db.setTransactionSuccessful();
942 } catch (SQLException ex) {
943 // Old version remains, which means we wipe old data
944 Log.e(TAG, ex.getMessage(), ex);
945 return false;
946 } finally {
947 db.endTransaction();
948 }
949 return true;
950 }
951
Kenny Guyed131872014-04-30 03:02:21 +0100952 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700953 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700954 }
955
956 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100957 db.beginTransaction();
958 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700959 db.execSQL("ALTER TABLE favorites ADD COLUMN "
960 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100961 db.setTransactionSuccessful();
962 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100963 Log.e(TAG, ex.getMessage(), ex);
964 return false;
965 } finally {
966 db.endTransaction();
967 }
968 return true;
969 }
970
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700971 // Generates a new ID to use for an object in your database. This method should be only
972 // called from the main UI thread. As an exception, we do call it when we call the
973 // constructor from the worker thread; however, this doesn't extend until after the
974 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
975 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700976 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700977 public long generateNewItemId() {
978 if (mMaxItemId < 0) {
979 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700980 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700981 mMaxItemId += 1;
982 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700983 }
984
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700985 @Override
986 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700987 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700988 }
989
Chris Wren5dee7af2013-12-20 17:22:11 -0500990 public void checkId(String table, ContentValues values) {
991 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700992 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500993 mMaxScreenId = Math.max(id, mMaxScreenId);
994 } else {
995 mMaxItemId = Math.max(id, mMaxItemId);
996 }
997 }
998
Adam Cohendcd297f2013-06-18 13:13:40 -0700999 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001000 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 }
1002
1003 // Generates a new ID to use for an workspace screen in your database. This method
1004 // should be only called from the main UI thread. As an exception, we do call it when we
1005 // call the constructor from the worker thread; however, this doesn't extend until after the
1006 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1007 // after that point
1008 public long generateNewScreenId() {
1009 if (mMaxScreenId < 0) {
1010 throw new RuntimeException("Error: max screen id was not initialized");
1011 }
1012 mMaxScreenId += 1;
1013 return mMaxScreenId;
1014 }
1015
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001017 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001018 }
1019
Adam Cohen091440a2015-03-18 14:16:05 -07001020 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001021 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001022 // TODO: Use multiple loaders with fall-back and transaction.
1023 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001024
1025 // Add the screens specified by the items above
1026 Collections.sort(screenIds);
1027 int rank = 0;
1028 ContentValues values = new ContentValues();
1029 for (Long id : screenIds) {
1030 values.clear();
1031 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1032 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001033 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001034 throw new RuntimeException("Failed initialize screen table"
1035 + "from default layout");
1036 }
1037 rank++;
1038 }
1039
1040 // Ensure that the max ids are initialized
1041 mMaxItemId = initializeMaxItemId(db);
1042 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001043
Adam Cohen71483f42014-05-15 14:04:01 -07001044 return count;
1045 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001046 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001047
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001048 /**
1049 * @return the max _id in the provided table.
1050 */
Adam Cohen091440a2015-03-18 14:16:05 -07001051 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001052 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1053 // get the result
1054 long id = -1;
1055 if (c != null && c.moveToNext()) {
1056 id = c.getLong(0);
1057 }
1058 if (c != null) {
1059 c.close();
1060 }
1061
1062 if (id == -1) {
1063 throw new RuntimeException("Error: could not query max id in " + table);
1064 }
1065
1066 return id;
1067 }
1068
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001069 static class SqlArguments {
1070 public final String table;
1071 public final String where;
1072 public final String[] args;
1073
1074 SqlArguments(Uri url, String where, String[] args) {
1075 if (url.getPathSegments().size() == 1) {
1076 this.table = url.getPathSegments().get(0);
1077 this.where = where;
1078 this.args = args;
1079 } else if (url.getPathSegments().size() != 2) {
1080 throw new IllegalArgumentException("Invalid URI: " + url);
1081 } else if (!TextUtils.isEmpty(where)) {
1082 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1083 } else {
1084 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001085 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001086 this.args = null;
1087 }
1088 }
1089
1090 SqlArguments(Uri url) {
1091 if (url.getPathSegments().size() == 1) {
1092 table = url.getPathSegments().get(0);
1093 where = null;
1094 args = null;
1095 } else {
1096 throw new IllegalArgumentException("Invalid URI: " + url);
1097 }
1098 }
1099 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001100
1101 private static class ChangeListenerWrapper implements Handler.Callback {
1102
1103 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1104 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1105 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1106
1107 private LauncherProviderChangeListener mListener;
1108
1109 @Override
1110 public boolean handleMessage(Message msg) {
1111 if (mListener != null) {
1112 switch (msg.what) {
1113 case MSG_LAUNCHER_PROVIDER_CHANGED:
1114 mListener.onLauncherProviderChange();
1115 break;
1116 case MSG_EXTRACTED_COLORS_CHANGED:
1117 mListener.onExtractedColorsChanged();
1118 break;
1119 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07001120 Context context = (Context) msg.obj;
1121 if (context != null) {
1122 context.sendBroadcast(new Intent(Launcher.ACTION_APPWIDGET_HOST_RESET)
1123 .setPackage(context.getPackageName()));
1124 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001125 break;
1126 }
1127 }
1128 return true;
1129 }
1130 }
Adam Cohen72960972014-01-15 18:13:55 -08001131}