blob: f5b32edda0614e79f8d7b5d44627275638b37e95 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
35import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.database.sqlite.SQLiteDatabase;
37import android.database.sqlite.SQLiteOpenHelper;
38import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070042import android.os.Build;
43import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070047import android.os.Trace;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070049import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070054import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.UserHandleCompat;
56import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070057import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040058import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070059import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070063import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Mike Cleronb87bd162009-10-30 16:36:56 -070067import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070068import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070069import java.util.Collections;
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 Goyala9e2f5a2016-06-10 12:22:04 -070075 private static final int DATABASE_VERSION = 27;
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 Goyale26d1002016-06-20 14:52:14 -070090 if (ProviderConfig.IS_DOGFOOD_BUILD) {
91 Log.d(TAG, "Launcher process started");
92 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -070093 mListenerHandler = new Handler(mListenerWrapper);
94
Daniel Sandlere4f98912013-06-25 15:13:26 -040095 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096 return true;
97 }
98
Sunny Goyald3849d12015-10-29 10:28:32 -070099 /**
100 * Sets a provider listener.
101 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700103 Preconditions.assertUIThread();
104 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700105 }
106
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107 @Override
108 public String getType(Uri uri) {
109 SqlArguments args = new SqlArguments(uri, null, null);
110 if (TextUtils.isEmpty(args.where)) {
111 return "vnd.android.cursor.dir/" + args.table;
112 } else {
113 return "vnd.android.cursor.item/" + args.table;
114 }
115 }
116
Sunny Goyalf076eae2016-01-11 12:25:10 -0800117 /**
118 * Overridden in tests
119 */
120 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700121 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700122 if (LauncherAppState.PROFILE_STARTUP) {
123 Trace.beginSection("Opening workspace DB");
124 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700125 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700126
127 if (RestoreDbTask.isPending(getContext())) {
128 if (!RestoreDbTask.performRestore(mOpenHelper)) {
129 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
130 }
131 // Set is pending to false irrespective of the result, so that it doesn't get
132 // executed again.
133 RestoreDbTask.setPending(getContext(), false);
134 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700135
136 if (LauncherAppState.PROFILE_STARTUP) {
137 Trace.endSection();
138 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700139 }
140 }
141
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800142 @Override
143 public Cursor query(Uri uri, String[] projection, String selection,
144 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700145 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800146
147 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
148 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
149 qb.setTables(args.table);
150
Romain Guy73b979d2009-06-09 12:57:21 -0700151 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
153 result.setNotificationUri(getContext().getContentResolver(), uri);
154
155 return result;
156 }
157
Adam Cohen091440a2015-03-18 14:16:05 -0700158 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500160 if (values == null) {
161 throw new RuntimeException("Error: attempting to insert null values");
162 }
Adam Cohen71483f42014-05-15 14:04:01 -0700163 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 throw new RuntimeException("Error: attempting to add item without specifying an id");
165 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500166 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700167 return db.insert(table, nullColumnHack, values);
168 }
169
Sunny Goyald1064182015-08-13 12:08:30 -0700170 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700171 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700172 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
173 if (app != null) {
174 app.reloadWorkspace();
175 }
176 }
177 }
178
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179 @Override
180 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700181 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 SqlArguments args = new SqlArguments(uri);
183
Sunny Goyald1064182015-08-13 12:08:30 -0700184 // In very limited cases, we support system|signature permission apps to modify the db.
185 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700186 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700187 return null;
188 }
189 }
190
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400192 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700193 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800194 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195
196 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700197 notifyListeners();
198
Sunny Goyalc74e4192015-09-08 14:01:03 -0700199 if (Utilities.ATLEAST_MARSHMALLOW) {
200 reloadLauncherIfExternal();
201 } else {
202 // Deprecated behavior to support legacy devices which rely on provider callbacks.
203 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
204 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
205 app.reloadWorkspace();
206 }
207
208 String notify = uri.getQueryParameter("notify");
209 if (notify == null || "true".equals(notify)) {
210 getContext().getContentResolver().notifyChange(uri, null);
211 }
212 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 return uri;
214 }
215
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700216 private boolean initializeExternalAdd(ContentValues values) {
217 // 1. Ensure that externally added items have a valid item id
218 long id = mOpenHelper.generateNewItemId();
219 values.put(LauncherSettings.Favorites._ID, id);
220
221 // 2. In the case of an app widget, and if no app widget id is specified, we
222 // attempt allocate and bind the widget.
223 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
224 if (itemType != null &&
225 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
226 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
227
228 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
229 ComponentName cn = ComponentName.unflattenFromString(
230 values.getAsString(Favorites.APPWIDGET_PROVIDER));
231
232 if (cn != null) {
233 try {
234 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
235 .allocateAppWidgetId();
236 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
237 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
238 return false;
239 }
240 } catch (RuntimeException e) {
241 Log.e(TAG, "Failed to initialize external widget", e);
242 return false;
243 }
244 } else {
245 return false;
246 }
247 }
248
249 // Add screen id if not present
250 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
251 SQLiteStatement stmp = null;
252 try {
253 stmp = mOpenHelper.getWritableDatabase().compileStatement(
254 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
255 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
256 stmp.bindLong(1, screenId);
257
258 ContentValues valuesInserted = new ContentValues();
259 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
260 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
261 return true;
262 } catch (Exception e) {
263 return false;
264 } finally {
265 Utilities.closeSilently(stmp);
266 }
267 }
268
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800269 @Override
270 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700271 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 SqlArguments args = new SqlArguments(uri);
273
274 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
275 db.beginTransaction();
276 try {
277 int numValues = values.length;
278 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400279 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700280 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
281 return 0;
282 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800283 }
284 db.setTransactionSuccessful();
285 } finally {
286 db.endTransaction();
287 }
288
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700289 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700290 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 return values.length;
292 }
293
294 @Override
Yura085c8532014-02-11 15:15:29 +0000295 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
296 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700297 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000298 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
299 db.beginTransaction();
300 try {
301 ContentProviderResult[] result = super.applyBatch(operations);
302 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700303 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000304 return result;
305 } finally {
306 db.endTransaction();
307 }
308 }
309
310 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800311 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700312 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
314
315 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
316 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700317 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318
Sunny Goyald1064182015-08-13 12:08:30 -0700319 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800320 return count;
321 }
322
323 @Override
324 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700325 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800326 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
327
Chris Wren1ada10d2013-09-13 18:01:38 -0400328 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
330 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700331 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332
Sunny Goyald1064182015-08-13 12:08:30 -0700333 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 return count;
335 }
336
Sunny Goyal7779d622015-06-11 16:18:39 -0700337 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700338 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700339 if (Binder.getCallingUid() != Process.myUid()) {
340 return null;
341 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700342 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700343
344 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700345 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
346 String extractedColors = extras.getString(
347 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
348 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
349 Utilities.getPrefs(getContext()).edit()
350 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
351 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
352 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700353 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700354 Bundle result = new Bundle();
355 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
356 return result;
357 }
Sunny Goyald2497482015-09-22 18:24:19 -0700358 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
359 clearFlagEmptyDbCreated();
360 return null;
361 }
362 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
363 Bundle result = new Bundle();
364 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
365 return result;
366 }
367 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
368 Bundle result = new Bundle();
369 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
370 return result;
371 }
372 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
373 Bundle result = new Bundle();
374 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
375 return result;
376 }
377 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
378 createEmptyDB();
379 return null;
380 }
381 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
382 loadDefaultFavoritesIfNecessary();
383 return null;
384 }
Sunny Goyald2497482015-09-22 18:24:19 -0700385 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
386 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
387 return null;
388 }
389 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
390 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
391 return null;
392 }
393 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800394 // Are you sure? (y/n)
395 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700396 return null;
397 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700398 }
399 return null;
400 }
401
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700402 /**
403 * Deletes any empty folder from the DB.
404 * @return Ids of deleted folders.
405 */
Sunny Goyald2497482015-09-22 18:24:19 -0700406 private ArrayList<Long> deleteEmptyFolders() {
407 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700408 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
409 db.beginTransaction();
410 try {
411 // Select folders whose id do not match any container value.
412 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
413 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
414 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
415 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700416 + Favorites.TABLE_NAME + ")";
417 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700418 new String[] {LauncherSettings.Favorites._ID},
419 selection, null, null, null, null);
420 while (c.moveToNext()) {
421 folderIds.add(c.getLong(0));
422 }
423 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700424 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700425 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700426 LauncherSettings.Favorites._ID, folderIds), null);
427 }
428 db.setTransactionSuccessful();
429 } catch (SQLException ex) {
430 Log.e(TAG, ex.getMessage(), ex);
431 folderIds.clear();
432 } finally {
433 db.endTransaction();
434 }
435 return folderIds;
436 }
437
Sunny Goyalf076eae2016-01-11 12:25:10 -0800438 /**
439 * Overridden in tests
440 */
441 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400442 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400443 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700444 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400445 }
446
Adam Cohen091440a2015-03-18 14:16:05 -0700447 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800449 }
450
Brian Muramatsu5524b492012-10-02 16:55:54 -0700451 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700452 * Clears all the data for a fresh start.
453 */
Sunny Goyald2497482015-09-22 18:24:19 -0700454 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700455 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
456 }
457
Sunny Goyald2497482015-09-22 18:24:19 -0700458 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700459 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700460 }
461
Sunny Goyal42de82f2014-09-26 22:09:29 -0700462 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700463 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700464 * 1) From the app restrictions
465 * 2) From a package provided by play store
466 * 3) From a partner configuration APK, already in the system image
467 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700468 */
Sunny Goyald2497482015-09-22 18:24:19 -0700469 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700470 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700471
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500473 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200474
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700475 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
476 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700477 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700478 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700479 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700481 final Partner partner = Partner.get(getContext().getPackageManager());
482 if (partner != null && partner.hasDefaultLayout()) {
483 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700484 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700485 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700486 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700487 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700488 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700489 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700490 }
491 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700492
Sunny Goyal9d219682014-10-23 14:21:02 -0700493 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700494 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700495 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700496 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800497
498 // There might be some partially restored DB items, due to buggy restore logic in
499 // previous versions of launcher.
500 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700501 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700502 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
503 && usingExternallyProvidedLayout) {
504 // Unable to load external layout. Cleanup and load the internal layout.
505 createEmptyDB();
506 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700507 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700508 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700509 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700510 }
511 }
512
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700513 /**
514 * Creates workspace loader from an XML resource listed in the app restrictions.
515 *
516 * @return the loader if the restrictions are set and the resource exists; null otherwise.
517 */
518 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700521 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700522 return null;
523 }
524
525 Context ctx = getContext();
526 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
527 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700528 if (bundle == null) {
529 return null;
530 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700531
Sunny Goyal35ca8732015-04-06 10:45:31 -0700532 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700533 if (packageName != null) {
534 try {
535 Resources targetResources = ctx.getPackageManager()
536 .getResourcesForApplication(packageName);
537 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700538 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700539 } catch (NameNotFoundException e) {
540 Log.e(TAG, "Target package for restricted profile not found", e);
541 return null;
542 }
543 }
544 return null;
545 }
546
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700547 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700548 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700549 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700551 mOpenHelper, getContext().getResources(), defaultLayout);
552 }
553
Sunny Goyald3849d12015-10-29 10:28:32 -0700554 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800555 * The class is subclassed in tests to create an in-memory db.
556 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700557 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700558 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700560 private long mMaxItemId = -1;
561 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800562
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700563 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
564 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700565 // Table creation sometimes fails silently, which leads to a crash loop.
566 // This way, we will try to create a table every time after crash, so the device
567 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700569 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
570 // This operation is a no-op if the table already exists.
571 addFavoritesTable(getWritableDatabase(), true);
572 addWorkspacesTable(getWritableDatabase(), true);
573 }
574
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700575 initIds();
576 }
577
578 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700579 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700580 */
581 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700582 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700583 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
584 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700585 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700586 }
587
588 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700589 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
590 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 if (mMaxItemId == -1) {
592 mMaxItemId = initializeMaxItemId(getWritableDatabase());
593 }
594 if (mMaxScreenId == -1) {
595 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700596 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 }
598
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700599 private boolean tableExists(String tableName) {
600 Cursor c = getReadableDatabase().query(
601 true, "sqlite_master", new String[] {"tbl_name"},
602 "tbl_name = ?", new String[] {tableName},
603 null, null, null, null, null);
604 try {
605 return c.getCount() > 0;
606 } finally {
607 c.close();
608 }
609 }
610
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 @Override
612 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800613 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700614
Adam Cohendcd297f2013-06-18 13:13:40 -0700615 mMaxItemId = 1;
616 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700617
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 addFavoritesTable(db, false);
619 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800621 // Fresh and clean launcher DB.
622 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800623 onEmptyDbCreated();
624 }
625
626 /**
627 * Overriden in tests.
628 */
629 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700630 // Database was just created, so wipe any previous widgets
631 if (mWidgetHostResetHandler != null) {
632 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyalda4fe1a2016-05-26 16:05:17 -0700633 mWidgetHostResetHandler.sendMessage(Message.obtain(
634 mWidgetHostResetHandler,
635 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET,
636 mContext
637 ));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700638 }
639
Sunny Goyalf076eae2016-01-11 12:25:10 -0800640 // Set the flag for empty DB
641 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700642
643 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800644 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
645 mContext);
646 }
647
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700648 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800649 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
650 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651 }
652
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700653 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700654 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700655 }
656
657 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
658 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700659 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800660 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400661 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
662 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700663 ");");
664 }
665
Adam Cohen119285e2014-04-02 16:59:08 -0700666 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700667 // Delete items directly on the workspace who's screen id doesn't exist
668 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
669 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700670 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700671 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700672 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700673 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700674 " AND " +
675 LauncherSettings.Favorites.CONTAINER + " = " +
676 LauncherSettings.Favorites.CONTAINER_DESKTOP;
677 db.execSQL(removeOrphanedDesktopItems);
678
679 // Delete items contained in folders which no longer exist (after above statement)
680 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
681 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700682 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700683 " WHERE " +
684 LauncherSettings.Favorites.CONTAINER + " <> " +
685 LauncherSettings.Favorites.CONTAINER_DESKTOP +
686 " AND "
687 + LauncherSettings.Favorites.CONTAINER + " <> " +
688 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
689 " AND "
690 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700691 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700692 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
693 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
694 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700695 }
696
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 @Override
698 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700699 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800700 switch (oldVersion) {
701 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800702 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800703 case 12: {
704 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
705 // to persist workspace screens and their relative order.
706 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700707 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800708 }
709 case 13: {
710 db.beginTransaction();
711 try {
712 // Insert new column for holding widget provider name
713 db.execSQL("ALTER TABLE favorites " +
714 "ADD COLUMN appWidgetProvider TEXT;");
715 db.setTransactionSuccessful();
716 } catch (SQLException ex) {
717 Log.e(TAG, ex.getMessage(), ex);
718 // Old version remains, which means we wipe old data
719 break;
720 } finally {
721 db.endTransaction();
722 }
723 }
724 case 14: {
725 db.beginTransaction();
726 try {
727 // Insert new column for holding update timestamp
728 db.execSQL("ALTER TABLE favorites " +
729 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
730 db.execSQL("ALTER TABLE workspaceScreens " +
731 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
732 db.setTransactionSuccessful();
733 } catch (SQLException ex) {
734 Log.e(TAG, ex.getMessage(), ex);
735 // Old version remains, which means we wipe old data
736 break;
737 } finally {
738 db.endTransaction();
739 }
740 }
741 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700742 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 // Old version remains, which means we wipe old data
744 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800745 }
746 }
747 case 16: {
748 // We use the db version upgrade here to identify users who may not have seen
749 // clings yet (because they weren't available), but for whom the clings are now
750 // available (tablet users). Because one of the possible cling flows (migration)
751 // is very destructive (wipes out workspaces), we want to prevent this from showing
752 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800753 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 }
755 case 17: {
756 // No-op
757 }
758 case 18: {
759 // Due to a data loss bug, some users may have items associated with screen ids
760 // which no longer exist. Since this can cause other problems, and since the user
761 // will never see these items anyway, we use database upgrade as an opportunity to
762 // clean things up.
763 removeOrphanedItems(db);
764 }
765 case 19: {
766 // Add userId column
767 if (!addProfileColumn(db)) {
768 // Old version remains, which means we wipe old data
769 break;
770 }
771 }
772 case 20:
773 if (!updateFolderItemsRank(db, true)) {
774 break;
775 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800776 case 21:
777 // Recreate workspace table with screen id a primary key
778 if (!recreateWorkspaceTable(db)) {
779 break;
780 }
781 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700782 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
783 // Old version remains, which means we wipe old data
784 break;
785 }
786 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700787 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700788 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700789 case 24:
790 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700791 case 25:
792 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700793 case 26:
794 // QSB was moved to the grid. Clear the first row on screen 0.
795 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
796 !LauncherDbUtils.prepareScreenZeroToHostQsb(db)) {
797 break;
798 }
799 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800800 // DB Upgraded successfully
801 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400802 }
803 }
804
Sunny Goyala2cc6242015-01-14 14:23:02 -0800805 // DB was not upgraded
806 Log.w(TAG, "Destroying all old data.");
807 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800808 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800809
Adam Cohen9b1d0622014-05-21 19:01:57 -0700810 @Override
811 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
812 // This shouldn't happen -- throw our hands up in the air and start over.
813 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
814 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700815 createEmptyDB(db);
816 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700817
Sunny Goyal42de82f2014-09-26 22:09:29 -0700818 /**
819 * Clears all the data for a fresh start.
820 */
821 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700822 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
823 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700824 onCreate(db);
825 }
826
Sunny Goyald2f38192015-02-25 10:46:34 -0800827 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700828 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
829 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
830 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700831 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700832 db.beginTransaction();
833 Cursor c = null;
834 SQLiteStatement updateStmt = null;
835
836 try {
837 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700838 long userSerial = getDefaultUserSerial();
839 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700840 Favorites._ID,
841 Favorites.INTENT,
842 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
843 null, null, null, null);
844
845 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
846 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
847
848 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
849 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
850
851 while (c.moveToNext()) {
852 String intentDescription = c.getString(intentIndex);
853 Intent intent;
854 try {
855 intent = Intent.parseUri(intentDescription, 0);
856 } catch (URISyntaxException e) {
857 Log.e(TAG, "Unable to parse intent", e);
858 continue;
859 }
860
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700861 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700862 continue;
863 }
864
865 long id = c.getLong(idIndex);
866 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700867 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700868 }
869 db.setTransactionSuccessful();
870 } catch (SQLException ex) {
871 Log.w(TAG, "Error deduping shortcuts", ex);
872 } finally {
873 db.endTransaction();
874 if (c != null) {
875 c.close();
876 }
877 if (updateStmt != null) {
878 updateStmt.close();
879 }
880 }
881 }
882
883 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800884 * Recreates workspace table and migrates data to the new table.
885 */
886 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
887 db.beginTransaction();
888 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700889 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800890 new String[] {LauncherSettings.WorkspaceScreens._ID},
891 null, null, null, null,
892 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
893 ArrayList<Long> sortedIDs = new ArrayList<Long>();
894 long maxId = 0;
895 try {
896 while (c.moveToNext()) {
897 Long id = c.getLong(0);
898 if (!sortedIDs.contains(id)) {
899 sortedIDs.add(id);
900 maxId = Math.max(maxId, id);
901 }
902 }
903 } finally {
904 c.close();
905 }
906
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700907 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700908 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800909
910 // Add all screen ids back
911 int total = sortedIDs.size();
912 for (int i = 0; i < total; i++) {
913 ContentValues values = new ContentValues();
914 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
915 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
916 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700917 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800918 }
919 db.setTransactionSuccessful();
920 mMaxScreenId = maxId;
921 } catch (SQLException ex) {
922 // Old version remains, which means we wipe old data
923 Log.e(TAG, ex.getMessage(), ex);
924 return false;
925 } finally {
926 db.endTransaction();
927 }
928 return true;
929 }
930
Adam Cohen091440a2015-03-18 14:16:05 -0700931 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800932 db.beginTransaction();
933 try {
934 if (addRankColumn) {
935 // Insert new column for holding rank
936 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
937 }
938
939 // Get a map for folder ID to folder width
940 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
941 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
942 + " GROUP BY container;",
943 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
944
945 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800946 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
947 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800948 new Object[] {c.getLong(1) + 1, c.getLong(0)});
949 }
950
951 c.close();
952 db.setTransactionSuccessful();
953 } catch (SQLException ex) {
954 // Old version remains, which means we wipe old data
955 Log.e(TAG, ex.getMessage(), ex);
956 return false;
957 } finally {
958 db.endTransaction();
959 }
960 return true;
961 }
962
Kenny Guyed131872014-04-30 03:02:21 +0100963 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700964 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700965 }
966
967 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100968 db.beginTransaction();
969 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700970 db.execSQL("ALTER TABLE favorites ADD COLUMN "
971 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100972 db.setTransactionSuccessful();
973 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100974 Log.e(TAG, ex.getMessage(), ex);
975 return false;
976 } finally {
977 db.endTransaction();
978 }
979 return true;
980 }
981
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700982 // Generates a new ID to use for an object in your database. This method should be only
983 // called from the main UI thread. As an exception, we do call it when we call the
984 // constructor from the worker thread; however, this doesn't extend until after the
985 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
986 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700987 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 public long generateNewItemId() {
989 if (mMaxItemId < 0) {
990 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700991 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700992 mMaxItemId += 1;
993 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700994 }
995
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700996 @Override
997 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700998 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700999 }
1000
Chris Wren5dee7af2013-12-20 17:22:11 -05001001 public void checkId(String table, ContentValues values) {
1002 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001003 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001004 mMaxScreenId = Math.max(id, mMaxScreenId);
1005 } else {
1006 mMaxItemId = Math.max(id, mMaxItemId);
1007 }
1008 }
1009
Adam Cohendcd297f2013-06-18 13:13:40 -07001010 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001011 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 }
1013
1014 // Generates a new ID to use for an workspace screen in your database. This method
1015 // should be only called from the main UI thread. As an exception, we do call it when we
1016 // call the constructor from the worker thread; however, this doesn't extend until after the
1017 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1018 // after that point
1019 public long generateNewScreenId() {
1020 if (mMaxScreenId < 0) {
1021 throw new RuntimeException("Error: max screen id was not initialized");
1022 }
1023 mMaxScreenId += 1;
1024 return mMaxScreenId;
1025 }
1026
Adam Cohendcd297f2013-06-18 13:13:40 -07001027 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001028 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001029 }
1030
Adam Cohen091440a2015-03-18 14:16:05 -07001031 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001032 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001033 // TODO: Use multiple loaders with fall-back and transaction.
1034 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001035
1036 // Add the screens specified by the items above
1037 Collections.sort(screenIds);
1038 int rank = 0;
1039 ContentValues values = new ContentValues();
1040 for (Long id : screenIds) {
1041 values.clear();
1042 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1043 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001044 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001045 throw new RuntimeException("Failed initialize screen table"
1046 + "from default layout");
1047 }
1048 rank++;
1049 }
1050
1051 // Ensure that the max ids are initialized
1052 mMaxItemId = initializeMaxItemId(db);
1053 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001054
Adam Cohen71483f42014-05-15 14:04:01 -07001055 return count;
1056 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001057 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001058
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001059 /**
1060 * @return the max _id in the provided table.
1061 */
Adam Cohen091440a2015-03-18 14:16:05 -07001062 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001063 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1064 // get the result
1065 long id = -1;
1066 if (c != null && c.moveToNext()) {
1067 id = c.getLong(0);
1068 }
1069 if (c != null) {
1070 c.close();
1071 }
1072
1073 if (id == -1) {
1074 throw new RuntimeException("Error: could not query max id in " + table);
1075 }
1076
1077 return id;
1078 }
1079
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001080 static class SqlArguments {
1081 public final String table;
1082 public final String where;
1083 public final String[] args;
1084
1085 SqlArguments(Uri url, String where, String[] args) {
1086 if (url.getPathSegments().size() == 1) {
1087 this.table = url.getPathSegments().get(0);
1088 this.where = where;
1089 this.args = args;
1090 } else if (url.getPathSegments().size() != 2) {
1091 throw new IllegalArgumentException("Invalid URI: " + url);
1092 } else if (!TextUtils.isEmpty(where)) {
1093 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1094 } else {
1095 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001096 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001097 this.args = null;
1098 }
1099 }
1100
1101 SqlArguments(Uri url) {
1102 if (url.getPathSegments().size() == 1) {
1103 table = url.getPathSegments().get(0);
1104 where = null;
1105 args = null;
1106 } else {
1107 throw new IllegalArgumentException("Invalid URI: " + url);
1108 }
1109 }
1110 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001111
1112 private static class ChangeListenerWrapper implements Handler.Callback {
1113
1114 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1115 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1116 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1117
1118 private LauncherProviderChangeListener mListener;
1119
1120 @Override
1121 public boolean handleMessage(Message msg) {
1122 if (mListener != null) {
1123 switch (msg.what) {
1124 case MSG_LAUNCHER_PROVIDER_CHANGED:
1125 mListener.onLauncherProviderChange();
1126 break;
1127 case MSG_EXTRACTED_COLORS_CHANGED:
1128 mListener.onExtractedColorsChanged();
1129 break;
1130 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07001131 Context context = (Context) msg.obj;
1132 if (context != null) {
1133 context.sendBroadcast(new Intent(Launcher.ACTION_APPWIDGET_HOST_RESET)
1134 .setPackage(context.getPackageName()));
1135 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001136 break;
1137 }
1138 }
1139 return true;
1140 }
1141 }
Adam Cohen72960972014-01-15 18:13:55 -08001142}