blob: a75040657008aa2f03cd2c723c3e5d487152b3ad [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
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070025import android.content.ContentUris;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000029import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070030import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070031import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070038import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070040import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070041import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070042import android.os.Handler;
43import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070044import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070045import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080046import android.os.UserHandle;
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.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070055import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070057import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyalfdbef272017-02-01 12:52:54 -080058import com.android.launcher3.logging.FileLog;
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;
Louis Begina9c21c62016-08-15 15:18:41 -070069import java.util.Locale;
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 Goyal24bb66a2017-03-21 15:12:01 -070075 private static final int DATABASE_VERSION = 28;
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
Sunny Goyalfdbef272017-02-01 12:52:54 -080095 // The content provider exists for the entire duration of the launcher main process and
96 // is the first component to get created. Initializing FileLog here ensures that it's
97 // always available in the main process.
98 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099 return true;
100 }
101
Sunny Goyald3849d12015-10-29 10:28:32 -0700102 /**
103 * Sets a provider listener.
104 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700105 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700106 Preconditions.assertUIThread();
107 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700108 }
109
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110 @Override
111 public String getType(Uri uri) {
112 SqlArguments args = new SqlArguments(uri, null, null);
113 if (TextUtils.isEmpty(args.where)) {
114 return "vnd.android.cursor.dir/" + args.table;
115 } else {
116 return "vnd.android.cursor.item/" + args.table;
117 }
118 }
119
Sunny Goyalf076eae2016-01-11 12:25:10 -0800120 /**
121 * Overridden in tests
122 */
123 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700124 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700125 if (LauncherAppState.PROFILE_STARTUP) {
126 Trace.beginSection("Opening workspace DB");
127 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700128 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700129
130 if (RestoreDbTask.isPending(getContext())) {
131 if (!RestoreDbTask.performRestore(mOpenHelper)) {
132 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
133 }
134 // Set is pending to false irrespective of the result, so that it doesn't get
135 // executed again.
136 RestoreDbTask.setPending(getContext(), false);
137 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700138
139 if (LauncherAppState.PROFILE_STARTUP) {
140 Trace.endSection();
141 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700142 }
143 }
144
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145 @Override
146 public Cursor query(Uri uri, String[] projection, String selection,
147 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700148 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149
150 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
151 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
152 qb.setTables(args.table);
153
Romain Guy73b979d2009-06-09 12:57:21 -0700154 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
156 result.setNotificationUri(getContext().getContentResolver(), uri);
157
158 return result;
159 }
160
Adam Cohen091440a2015-03-18 14:16:05 -0700161 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500163 if (values == null) {
164 throw new RuntimeException("Error: attempting to insert null values");
165 }
Adam Cohen71483f42014-05-15 14:04:01 -0700166 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700167 throw new RuntimeException("Error: attempting to add item without specifying an id");
168 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500169 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700170 return db.insert(table, nullColumnHack, values);
171 }
172
Sunny Goyald1064182015-08-13 12:08:30 -0700173 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700174 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700175 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
176 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800177 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700178 }
179 }
180 }
181
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 @Override
183 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700184 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185 SqlArguments args = new SqlArguments(uri);
186
Sunny Goyald1064182015-08-13 12:08:30 -0700187 // In very limited cases, we support system|signature permission apps to modify the db.
188 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700189 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700190 return null;
191 }
192 }
193
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700196 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800197 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198
199 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700200 notifyListeners();
201
Sunny Goyalc74e4192015-09-08 14:01:03 -0700202 if (Utilities.ATLEAST_MARSHMALLOW) {
203 reloadLauncherIfExternal();
204 } else {
205 // Deprecated behavior to support legacy devices which rely on provider callbacks.
206 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
207 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800208 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700209 }
210
211 String notify = uri.getQueryParameter("notify");
212 if (notify == null || "true".equals(notify)) {
213 getContext().getContentResolver().notifyChange(uri, null);
214 }
215 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 return uri;
217 }
218
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700219 private boolean initializeExternalAdd(ContentValues values) {
220 // 1. Ensure that externally added items have a valid item id
221 long id = mOpenHelper.generateNewItemId();
222 values.put(LauncherSettings.Favorites._ID, id);
223
224 // 2. In the case of an app widget, and if no app widget id is specified, we
225 // attempt allocate and bind the widget.
226 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
227 if (itemType != null &&
228 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
229 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
230
231 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
232 ComponentName cn = ComponentName.unflattenFromString(
233 values.getAsString(Favorites.APPWIDGET_PROVIDER));
234
235 if (cn != null) {
236 try {
237 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
238 .allocateAppWidgetId();
239 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
240 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
241 return false;
242 }
243 } catch (RuntimeException e) {
244 Log.e(TAG, "Failed to initialize external widget", e);
245 return false;
246 }
247 } else {
248 return false;
249 }
250 }
251
252 // Add screen id if not present
253 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
254 SQLiteStatement stmp = null;
255 try {
256 stmp = mOpenHelper.getWritableDatabase().compileStatement(
257 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
258 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
259 stmp.bindLong(1, screenId);
260
261 ContentValues valuesInserted = new ContentValues();
262 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
263 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
264 return true;
265 } catch (Exception e) {
266 return false;
267 } finally {
268 Utilities.closeSilently(stmp);
269 }
270 }
271
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 @Override
273 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700274 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 SqlArguments args = new SqlArguments(uri);
276
277 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
278 db.beginTransaction();
279 try {
280 int numValues = values.length;
281 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400282 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700283 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
284 return 0;
285 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800286 }
287 db.setTransactionSuccessful();
288 } finally {
289 db.endTransaction();
290 }
291
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700292 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700293 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 return values.length;
295 }
296
297 @Override
Yura085c8532014-02-11 15:15:29 +0000298 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
299 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700300 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000301 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
302 db.beginTransaction();
303 try {
304 ContentProviderResult[] result = super.applyBatch(operations);
305 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700306 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000307 return result;
308 } finally {
309 db.endTransaction();
310 }
311 }
312
313 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800314 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700315 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800316 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
317
318 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800319
Louis Begina9c21c62016-08-15 15:18:41 -0700320 if (Binder.getCallingPid() != Process.myPid()
321 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
322 String widgetSelection = TextUtils.isEmpty(args.where) ? "1=1" : args.where;
323 widgetSelection = String.format(Locale.ENGLISH, "%1$s = %2$d AND ( %3$s )",
324 Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET, widgetSelection);
325 try (Cursor c = db.query(Favorites.TABLE_NAME, new String[] { Favorites.APPWIDGET_ID },
326 widgetSelection, args.args, null, null, null)) {
327 AppWidgetHost host = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
328 while (c.moveToNext()) {
329 int widgetId = c.getInt(0);
330 if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
331 try {
332 host.deleteAppWidgetId(widgetId);
333 } catch (RuntimeException e) {
334 Log.e(TAG, "Error deleting widget id " + widgetId, e);
335 }
336 }
337 }
338 }
339 }
340 int count = db.delete(args.table, args.where, args.args);
341 if (count > 0) {
342 notifyListeners();
343 reloadLauncherIfExternal();
344 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 return count;
346 }
347
348 @Override
349 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700350 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
352
Chris Wren1ada10d2013-09-13 18:01:38 -0400353 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
355 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700356 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357
Sunny Goyald1064182015-08-13 12:08:30 -0700358 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 return count;
360 }
361
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700363 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700364 if (Binder.getCallingUid() != Process.myUid()) {
365 return null;
366 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700367 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700368
369 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700370 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
371 String extractedColors = extras.getString(
372 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
373 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
374 Utilities.getPrefs(getContext()).edit()
375 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
376 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
377 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700378 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700379 Bundle result = new Bundle();
380 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
381 return result;
382 }
Sunny Goyald2497482015-09-22 18:24:19 -0700383 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
384 clearFlagEmptyDbCreated();
385 return null;
386 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700387 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
388 Bundle result = new Bundle();
389 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
390 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
391 return result;
392 }
Sunny Goyald2497482015-09-22 18:24:19 -0700393 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
394 Bundle result = new Bundle();
395 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
396 return result;
397 }
398 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
399 Bundle result = new Bundle();
400 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
401 return result;
402 }
403 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
404 Bundle result = new Bundle();
405 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
406 return result;
407 }
408 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800409 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700410 return null;
411 }
412 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
413 loadDefaultFavoritesIfNecessary();
414 return null;
415 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700416 }
417 return null;
418 }
419
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700420 /**
421 * Deletes any empty folder from the DB.
422 * @return Ids of deleted folders.
423 */
Sunny Goyald2497482015-09-22 18:24:19 -0700424 private ArrayList<Long> deleteEmptyFolders() {
425 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700426 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
427 db.beginTransaction();
428 try {
429 // Select folders whose id do not match any container value.
430 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
431 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
432 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
433 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700434 + Favorites.TABLE_NAME + ")";
435 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700436 new String[] {LauncherSettings.Favorites._ID},
437 selection, null, null, null, null);
438 while (c.moveToNext()) {
439 folderIds.add(c.getLong(0));
440 }
441 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700442 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700443 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700444 LauncherSettings.Favorites._ID, folderIds), null);
445 }
446 db.setTransactionSuccessful();
447 } catch (SQLException ex) {
448 Log.e(TAG, ex.getMessage(), ex);
449 folderIds.clear();
450 } finally {
451 db.endTransaction();
452 }
453 return folderIds;
454 }
455
Sunny Goyalf076eae2016-01-11 12:25:10 -0800456 /**
457 * Overridden in tests
458 */
459 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700460 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400461 }
462
Adam Cohen091440a2015-03-18 14:16:05 -0700463 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400464 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465 }
466
Sunny Goyald2497482015-09-22 18:24:19 -0700467 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700468 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700469 }
470
Sunny Goyal42de82f2014-09-26 22:09:29 -0700471 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700472 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700473 * 1) From the app restrictions
474 * 2) From a package provided by play store
475 * 3) From a partner configuration APK, already in the system image
476 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700477 */
Sunny Goyald2497482015-09-22 18:24:19 -0700478 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700479 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700480
Winson Chungc763c4e2013-07-19 13:49:06 -0700481 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500482 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200483
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700484 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
485 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700486 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700487 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700488 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700489 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700490 final Partner partner = Partner.get(getContext().getPackageManager());
491 if (partner != null && partner.hasDefaultLayout()) {
492 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700493 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700494 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700495 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700496 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700497 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700498 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700499 }
500 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700501
Sunny Goyal9d219682014-10-23 14:21:02 -0700502 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700503 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700504 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700505 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800506
507 // There might be some partially restored DB items, due to buggy restore logic in
508 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800509 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700510 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700511 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
512 && usingExternallyProvidedLayout) {
513 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800514 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700515 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700516 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700517 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700518 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700519 }
520 }
521
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700522 /**
523 * Creates workspace loader from an XML resource listed in the app restrictions.
524 *
525 * @return the loader if the restrictions are set and the resource exists; null otherwise.
526 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700527 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700528 Context ctx = getContext();
529 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
530 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700531 if (bundle == null) {
532 return null;
533 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700534
Sunny Goyal35ca8732015-04-06 10:45:31 -0700535 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700536 if (packageName != null) {
537 try {
538 Resources targetResources = ctx.getPackageManager()
539 .getResourcesForApplication(packageName);
540 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700541 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700542 } catch (NameNotFoundException e) {
543 Log.e(TAG, "Target package for restricted profile not found", e);
544 return null;
545 }
546 }
547 return null;
548 }
549
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800551 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700552 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700553 mOpenHelper, getContext().getResources(), defaultLayout);
554 }
555
Sunny Goyald3849d12015-10-29 10:28:32 -0700556 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800557 * The class is subclassed in tests to create an in-memory db.
558 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700559 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700560 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700562 private long mMaxItemId = -1;
563 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800564
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700565 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
566 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700567 // Table creation sometimes fails silently, which leads to a crash loop.
568 // This way, we will try to create a table every time after crash, so the device
569 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700570 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700571 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
572 // This operation is a no-op if the table already exists.
573 addFavoritesTable(getWritableDatabase(), true);
574 addWorkspacesTable(getWritableDatabase(), true);
575 }
576
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 initIds();
578 }
579
580 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700581 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700582 */
583 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700584 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700585 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
586 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700587 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700588 }
589
590 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700591 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
592 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700593 if (mMaxItemId == -1) {
594 mMaxItemId = initializeMaxItemId(getWritableDatabase());
595 }
596 if (mMaxScreenId == -1) {
597 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700598 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
600
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700601 private boolean tableExists(String tableName) {
602 Cursor c = getReadableDatabase().query(
603 true, "sqlite_master", new String[] {"tbl_name"},
604 "tbl_name = ?", new String[] {tableName},
605 null, null, null, null, null);
606 try {
607 return c.getCount() > 0;
608 } finally {
609 c.close();
610 }
611 }
612
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613 @Override
614 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800615 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700616
Adam Cohendcd297f2013-06-18 13:13:40 -0700617 mMaxItemId = 1;
618 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700619
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700620 addFavoritesTable(db, false);
621 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800623 // Fresh and clean launcher DB.
624 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800625 onEmptyDbCreated();
626 }
627
628 /**
629 * Overriden in tests.
630 */
631 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700632 // Database was just created, so wipe any previous widgets
633 if (mWidgetHostResetHandler != null) {
634 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700635 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530636 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700637 }
638
Sunny Goyalf076eae2016-01-11 12:25:10 -0800639 // Set the flag for empty DB
640 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700641
642 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800643 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800644 mContext);
645 }
646
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700647 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800648 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800649 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 }
651
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700652 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700653 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700654 }
655
656 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
657 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700658 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800659 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400660 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
661 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700662 ");");
663 }
664
Adam Cohen119285e2014-04-02 16:59:08 -0700665 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700666 // Delete items directly on the workspace who's screen id doesn't exist
667 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
668 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700669 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700670 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700671 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700672 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 " AND " +
674 LauncherSettings.Favorites.CONTAINER + " = " +
675 LauncherSettings.Favorites.CONTAINER_DESKTOP;
676 db.execSQL(removeOrphanedDesktopItems);
677
678 // Delete items contained in folders which no longer exist (after above statement)
679 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
680 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700681 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700682 " WHERE " +
683 LauncherSettings.Favorites.CONTAINER + " <> " +
684 LauncherSettings.Favorites.CONTAINER_DESKTOP +
685 " AND "
686 + LauncherSettings.Favorites.CONTAINER + " <> " +
687 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
688 " AND "
689 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700690 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700691 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
692 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
693 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700694 }
695
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800696 @Override
697 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700698 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800699 switch (oldVersion) {
700 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800701 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 case 12: {
703 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
704 // to persist workspace screens and their relative order.
705 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700706 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800707 }
708 case 13: {
709 db.beginTransaction();
710 try {
711 // Insert new column for holding widget provider name
712 db.execSQL("ALTER TABLE favorites " +
713 "ADD COLUMN appWidgetProvider TEXT;");
714 db.setTransactionSuccessful();
715 } catch (SQLException ex) {
716 Log.e(TAG, ex.getMessage(), ex);
717 // Old version remains, which means we wipe old data
718 break;
719 } finally {
720 db.endTransaction();
721 }
722 }
723 case 14: {
724 db.beginTransaction();
725 try {
726 // Insert new column for holding update timestamp
727 db.execSQL("ALTER TABLE favorites " +
728 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
729 db.execSQL("ALTER TABLE workspaceScreens " +
730 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
731 db.setTransactionSuccessful();
732 } catch (SQLException ex) {
733 Log.e(TAG, ex.getMessage(), ex);
734 // Old version remains, which means we wipe old data
735 break;
736 } finally {
737 db.endTransaction();
738 }
739 }
740 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700741 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 // Old version remains, which means we wipe old data
743 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800744 }
745 }
746 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700747 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 }
749 case 17: {
750 // No-op
751 }
752 case 18: {
753 // Due to a data loss bug, some users may have items associated with screen ids
754 // which no longer exist. Since this can cause other problems, and since the user
755 // will never see these items anyway, we use database upgrade as an opportunity to
756 // clean things up.
757 removeOrphanedItems(db);
758 }
759 case 19: {
760 // Add userId column
761 if (!addProfileColumn(db)) {
762 // Old version remains, which means we wipe old data
763 break;
764 }
765 }
766 case 20:
767 if (!updateFolderItemsRank(db, true)) {
768 break;
769 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800770 case 21:
771 // Recreate workspace table with screen id a primary key
772 if (!recreateWorkspaceTable(db)) {
773 break;
774 }
775 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700776 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
777 // Old version remains, which means we wipe old data
778 break;
779 }
780 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700781 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700782 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700783 case 24:
784 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700785 case 25:
786 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700787 case 26:
788 // QSB was moved to the grid. Clear the first row on screen 0.
789 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800790 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700791 break;
792 }
793 case 27: {
Sunny Goyal24bb66a2017-03-21 15:12:01 -0700794 // Remove "profile extra"
795 db.beginTransaction();
796 try {
797 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
798 for (UserHandle user : um.getUserProfiles()) {
799 long serial = um.getSerialNumberForUser(user);
800 String sql = "update favorites set intent = replace(intent, "
801 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
802 db.execSQL(sql);
803 }
804 db.setTransactionSuccessful();
805 } catch (SQLException ex) {
806 Log.e(TAG, ex.getMessage(), ex);
807 // Old version remains, which means we wipe old data
808 break;
809 } finally {
810 db.endTransaction();
811 }
812 }
813 case 28: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 // DB Upgraded successfully
815 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400816 }
817 }
818
Sunny Goyala2cc6242015-01-14 14:23:02 -0800819 // DB was not upgraded
820 Log.w(TAG, "Destroying all old data.");
821 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800822 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800823
Adam Cohen9b1d0622014-05-21 19:01:57 -0700824 @Override
825 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
826 // This shouldn't happen -- throw our hands up in the air and start over.
827 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
828 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700829 createEmptyDB(db);
830 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700831
Sunny Goyal42de82f2014-09-26 22:09:29 -0700832 /**
833 * Clears all the data for a fresh start.
834 */
835 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800836 db.beginTransaction();
837 try {
838 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
839 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
840 onCreate(db);
841 db.setTransactionSuccessful();
842 } finally {
843 db.endTransaction();
844 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700845 }
846
Sunny Goyald2f38192015-02-25 10:46:34 -0800847 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
849 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
850 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700851 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 db.beginTransaction();
853 Cursor c = null;
854 SQLiteStatement updateStmt = null;
855
856 try {
857 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700858 long userSerial = getDefaultUserSerial();
859 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700860 Favorites._ID,
861 Favorites.INTENT,
862 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
863 null, null, null, null);
864
865 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
866 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
867
868 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
869 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
870
871 while (c.moveToNext()) {
872 String intentDescription = c.getString(intentIndex);
873 Intent intent;
874 try {
875 intent = Intent.parseUri(intentDescription, 0);
876 } catch (URISyntaxException e) {
877 Log.e(TAG, "Unable to parse intent", e);
878 continue;
879 }
880
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700881 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700882 continue;
883 }
884
885 long id = c.getLong(idIndex);
886 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700887 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700888 }
889 db.setTransactionSuccessful();
890 } catch (SQLException ex) {
891 Log.w(TAG, "Error deduping shortcuts", ex);
892 } finally {
893 db.endTransaction();
894 if (c != null) {
895 c.close();
896 }
897 if (updateStmt != null) {
898 updateStmt.close();
899 }
900 }
901 }
902
903 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800904 * Recreates workspace table and migrates data to the new table.
905 */
906 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
907 db.beginTransaction();
908 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700909 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800910 new String[] {LauncherSettings.WorkspaceScreens._ID},
911 null, null, null, null,
912 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
913 ArrayList<Long> sortedIDs = new ArrayList<Long>();
914 long maxId = 0;
915 try {
916 while (c.moveToNext()) {
917 Long id = c.getLong(0);
918 if (!sortedIDs.contains(id)) {
919 sortedIDs.add(id);
920 maxId = Math.max(maxId, id);
921 }
922 }
923 } finally {
924 c.close();
925 }
926
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700927 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700928 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800929
930 // Add all screen ids back
931 int total = sortedIDs.size();
932 for (int i = 0; i < total; i++) {
933 ContentValues values = new ContentValues();
934 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
935 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
936 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700937 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800938 }
939 db.setTransactionSuccessful();
940 mMaxScreenId = maxId;
941 } catch (SQLException ex) {
942 // Old version remains, which means we wipe old data
943 Log.e(TAG, ex.getMessage(), ex);
944 return false;
945 } finally {
946 db.endTransaction();
947 }
948 return true;
949 }
950
Adam Cohen091440a2015-03-18 14:16:05 -0700951 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800952 db.beginTransaction();
953 try {
954 if (addRankColumn) {
955 // Insert new column for holding rank
956 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
957 }
958
959 // Get a map for folder ID to folder width
960 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
961 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
962 + " GROUP BY container;",
963 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
964
965 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800966 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
967 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800968 new Object[] {c.getLong(1) + 1, c.getLong(0)});
969 }
970
971 c.close();
972 db.setTransactionSuccessful();
973 } catch (SQLException ex) {
974 // Old version remains, which means we wipe old data
975 Log.e(TAG, ex.getMessage(), ex);
976 return false;
977 } finally {
978 db.endTransaction();
979 }
980 return true;
981 }
982
Kenny Guyed131872014-04-30 03:02:21 +0100983 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700984 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700985 }
986
987 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100988 db.beginTransaction();
989 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700990 db.execSQL("ALTER TABLE favorites ADD COLUMN "
991 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100992 db.setTransactionSuccessful();
993 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100994 Log.e(TAG, ex.getMessage(), ex);
995 return false;
996 } finally {
997 db.endTransaction();
998 }
999 return true;
1000 }
1001
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001002 // Generates a new ID to use for an object in your database. This method should be only
1003 // called from the main UI thread. As an exception, we do call it when we call the
1004 // constructor from the worker thread; however, this doesn't extend until after the
1005 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1006 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001007 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001008 public long generateNewItemId() {
1009 if (mMaxItemId < 0) {
1010 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001011 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 mMaxItemId += 1;
1013 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001014 }
1015
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001016 @Override
1017 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001018 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001019 }
1020
Chris Wren5dee7af2013-12-20 17:22:11 -05001021 public void checkId(String table, ContentValues values) {
1022 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001023 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001024 mMaxScreenId = Math.max(id, mMaxScreenId);
1025 } else {
1026 mMaxItemId = Math.max(id, mMaxItemId);
1027 }
1028 }
1029
Adam Cohendcd297f2013-06-18 13:13:40 -07001030 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001031 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001032 }
1033
1034 // Generates a new ID to use for an workspace screen in your database. This method
1035 // should be only called from the main UI thread. As an exception, we do call it when we
1036 // call the constructor from the worker thread; however, this doesn't extend until after the
1037 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1038 // after that point
1039 public long generateNewScreenId() {
1040 if (mMaxScreenId < 0) {
1041 throw new RuntimeException("Error: max screen id was not initialized");
1042 }
1043 mMaxScreenId += 1;
1044 return mMaxScreenId;
1045 }
1046
Adam Cohendcd297f2013-06-18 13:13:40 -07001047 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001048 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001049 }
1050
Adam Cohen091440a2015-03-18 14:16:05 -07001051 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001052 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001053 // TODO: Use multiple loaders with fall-back and transaction.
1054 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001055
1056 // Add the screens specified by the items above
1057 Collections.sort(screenIds);
1058 int rank = 0;
1059 ContentValues values = new ContentValues();
1060 for (Long id : screenIds) {
1061 values.clear();
1062 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1063 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001064 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001065 throw new RuntimeException("Failed initialize screen table"
1066 + "from default layout");
1067 }
1068 rank++;
1069 }
1070
1071 // Ensure that the max ids are initialized
1072 mMaxItemId = initializeMaxItemId(db);
1073 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001074
Adam Cohen71483f42014-05-15 14:04:01 -07001075 return count;
1076 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001077 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001078
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001079 /**
1080 * @return the max _id in the provided table.
1081 */
Adam Cohen091440a2015-03-18 14:16:05 -07001082 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001083 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1084 // get the result
1085 long id = -1;
1086 if (c != null && c.moveToNext()) {
1087 id = c.getLong(0);
1088 }
1089 if (c != null) {
1090 c.close();
1091 }
1092
1093 if (id == -1) {
1094 throw new RuntimeException("Error: could not query max id in " + table);
1095 }
1096
1097 return id;
1098 }
1099
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001100 static class SqlArguments {
1101 public final String table;
1102 public final String where;
1103 public final String[] args;
1104
1105 SqlArguments(Uri url, String where, String[] args) {
1106 if (url.getPathSegments().size() == 1) {
1107 this.table = url.getPathSegments().get(0);
1108 this.where = where;
1109 this.args = args;
1110 } else if (url.getPathSegments().size() != 2) {
1111 throw new IllegalArgumentException("Invalid URI: " + url);
1112 } else if (!TextUtils.isEmpty(where)) {
1113 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1114 } else {
1115 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001116 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001117 this.args = null;
1118 }
1119 }
1120
1121 SqlArguments(Uri url) {
1122 if (url.getPathSegments().size() == 1) {
1123 table = url.getPathSegments().get(0);
1124 where = null;
1125 args = null;
1126 } else {
1127 throw new IllegalArgumentException("Invalid URI: " + url);
1128 }
1129 }
1130 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001131
1132 private static class ChangeListenerWrapper implements Handler.Callback {
1133
1134 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1135 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1136 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1137
1138 private LauncherProviderChangeListener mListener;
1139
1140 @Override
1141 public boolean handleMessage(Message msg) {
1142 if (mListener != null) {
1143 switch (msg.what) {
1144 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001145 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001146 break;
1147 case MSG_EXTRACTED_COLORS_CHANGED:
1148 mListener.onExtractedColorsChanged();
1149 break;
1150 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001151 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001152 break;
1153 }
1154 }
1155 return true;
1156 }
1157 }
Adam Cohen72960972014-01-15 18:13:55 -08001158}