blob: 65d76728d2493f3bbae06ab6d3565421a626114f [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;
Hyunyoung Songe295aca2017-02-06 10:46:24 -080050import android.view.ViewGroup;
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.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070056import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040057import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070058import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyalca187462017-03-31 20:09:34 -070059import com.android.launcher3.graphics.IconShapeOverride;
Sunny Goyalfdbef272017-02-01 12:52:54 -080060import com.android.launcher3.logging.FileLog;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070061import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070062import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070063import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070064import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070065import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070066import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070067
Hyunyoung Songe295aca2017-02-06 10:46:24 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070070import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070071import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070072import java.util.Collections;
Louis Begina9c21c62016-08-15 15:18:41 -070073import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070076 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080077 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Sunny Goyal24bb66a2017-03-21 15:12:01 -070079 private static final int DATABASE_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyale5bb7052015-07-27 14:36:07 -070081 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070082
Sunny Goyale87e6ab2014-11-21 22:42:53 -080083 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070085 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
86
Sunny Goyalb5b55c82016-05-10 12:28:59 -070087 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
88 private Handler mListenerHandler;
89
Sunny Goyalf076eae2016-01-11 12:25:10 -080090 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Hyunyoung Songe295aca2017-02-06 10:46:24 -080092 /**
93 * $ adb shell dumpsys activity provider com.android.launcher3
94 */
95 @Override
96 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
97 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
98 if (appState == null || !appState.getModel().isModelLoaded()) {
99 return;
100 }
101 appState.getModel().dumpState("", fd, writer, args);
102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public boolean onCreate() {
Sunny Goyale26d1002016-06-20 14:52:14 -0700106 if (ProviderConfig.IS_DOGFOOD_BUILD) {
107 Log.d(TAG, "Launcher process started");
108 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700109 mListenerHandler = new Handler(mListenerWrapper);
110
Sunny Goyalfdbef272017-02-01 12:52:54 -0800111 // The content provider exists for the entire duration of the launcher main process and
112 // is the first component to get created. Initializing FileLog here ensures that it's
113 // always available in the main process.
114 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700115 IconShapeOverride.apply(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116 return true;
117 }
118
Sunny Goyald3849d12015-10-29 10:28:32 -0700119 /**
120 * Sets a provider listener.
121 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700122 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700123 Preconditions.assertUIThread();
124 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700125 }
126
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127 @Override
128 public String getType(Uri uri) {
129 SqlArguments args = new SqlArguments(uri, null, null);
130 if (TextUtils.isEmpty(args.where)) {
131 return "vnd.android.cursor.dir/" + args.table;
132 } else {
133 return "vnd.android.cursor.item/" + args.table;
134 }
135 }
136
Sunny Goyalf076eae2016-01-11 12:25:10 -0800137 /**
138 * Overridden in tests
139 */
140 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700141 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700142 if (LauncherAppState.PROFILE_STARTUP) {
143 Trace.beginSection("Opening workspace DB");
144 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700145 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700146
147 if (RestoreDbTask.isPending(getContext())) {
148 if (!RestoreDbTask.performRestore(mOpenHelper)) {
149 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
150 }
151 // Set is pending to false irrespective of the result, so that it doesn't get
152 // executed again.
153 RestoreDbTask.setPending(getContext(), false);
154 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700155
156 if (LauncherAppState.PROFILE_STARTUP) {
157 Trace.endSection();
158 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700159 }
160 }
161
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800162 @Override
163 public Cursor query(Uri uri, String[] projection, String selection,
164 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700165 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166
167 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
168 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
169 qb.setTables(args.table);
170
Romain Guy73b979d2009-06-09 12:57:21 -0700171 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
173 result.setNotificationUri(getContext().getContentResolver(), uri);
174
175 return result;
176 }
177
Adam Cohen091440a2015-03-18 14:16:05 -0700178 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700179 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500180 if (values == null) {
181 throw new RuntimeException("Error: attempting to insert null values");
182 }
Adam Cohen71483f42014-05-15 14:04:01 -0700183 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 throw new RuntimeException("Error: attempting to add item without specifying an id");
185 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500186 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700187 return db.insert(table, nullColumnHack, values);
188 }
189
Sunny Goyald1064182015-08-13 12:08:30 -0700190 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700191 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700192 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
193 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800194 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700195 }
196 }
197 }
198
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199 @Override
200 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700201 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 SqlArguments args = new SqlArguments(uri);
203
Sunny Goyald1064182015-08-13 12:08:30 -0700204 // In very limited cases, we support system|signature permission apps to modify the db.
205 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700206 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700207 return null;
208 }
209 }
210
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400212 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700213 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800214 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215
216 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700217 notifyListeners();
218
Sunny Goyalc74e4192015-09-08 14:01:03 -0700219 if (Utilities.ATLEAST_MARSHMALLOW) {
220 reloadLauncherIfExternal();
221 } else {
222 // Deprecated behavior to support legacy devices which rely on provider callbacks.
223 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
224 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800225 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700226 }
227
228 String notify = uri.getQueryParameter("notify");
229 if (notify == null || "true".equals(notify)) {
230 getContext().getContentResolver().notifyChange(uri, null);
231 }
232 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 return uri;
234 }
235
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700236 private boolean initializeExternalAdd(ContentValues values) {
237 // 1. Ensure that externally added items have a valid item id
238 long id = mOpenHelper.generateNewItemId();
239 values.put(LauncherSettings.Favorites._ID, id);
240
241 // 2. In the case of an app widget, and if no app widget id is specified, we
242 // attempt allocate and bind the widget.
243 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
244 if (itemType != null &&
245 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
246 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
247
248 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
249 ComponentName cn = ComponentName.unflattenFromString(
250 values.getAsString(Favorites.APPWIDGET_PROVIDER));
251
252 if (cn != null) {
253 try {
254 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
255 .allocateAppWidgetId();
256 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
257 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
258 return false;
259 }
260 } catch (RuntimeException e) {
261 Log.e(TAG, "Failed to initialize external widget", e);
262 return false;
263 }
264 } else {
265 return false;
266 }
267 }
268
269 // Add screen id if not present
270 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
271 SQLiteStatement stmp = null;
272 try {
273 stmp = mOpenHelper.getWritableDatabase().compileStatement(
274 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
275 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
276 stmp.bindLong(1, screenId);
277
278 ContentValues valuesInserted = new ContentValues();
279 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
280 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
281 return true;
282 } catch (Exception e) {
283 return false;
284 } finally {
285 Utilities.closeSilently(stmp);
286 }
287 }
288
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800289 @Override
290 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700291 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 SqlArguments args = new SqlArguments(uri);
293
294 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
295 db.beginTransaction();
296 try {
297 int numValues = values.length;
298 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400299 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700300 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
301 return 0;
302 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 }
304 db.setTransactionSuccessful();
305 } finally {
306 db.endTransaction();
307 }
308
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700309 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700310 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800311 return values.length;
312 }
313
314 @Override
Yura085c8532014-02-11 15:15:29 +0000315 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
316 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700317 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000318 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
319 db.beginTransaction();
320 try {
321 ContentProviderResult[] result = super.applyBatch(operations);
322 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700323 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000324 return result;
325 } finally {
326 db.endTransaction();
327 }
328 }
329
330 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700332 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
334
335 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336
Louis Begina9c21c62016-08-15 15:18:41 -0700337 if (Binder.getCallingPid() != Process.myPid()
338 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
339 String widgetSelection = TextUtils.isEmpty(args.where) ? "1=1" : args.where;
340 widgetSelection = String.format(Locale.ENGLISH, "%1$s = %2$d AND ( %3$s )",
341 Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET, widgetSelection);
342 try (Cursor c = db.query(Favorites.TABLE_NAME, new String[] { Favorites.APPWIDGET_ID },
343 widgetSelection, args.args, null, null, null)) {
344 AppWidgetHost host = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
345 while (c.moveToNext()) {
346 int widgetId = c.getInt(0);
347 if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
348 try {
349 host.deleteAppWidgetId(widgetId);
350 } catch (RuntimeException e) {
351 Log.e(TAG, "Error deleting widget id " + widgetId, e);
352 }
353 }
354 }
355 }
356 }
357 int count = db.delete(args.table, args.where, args.args);
358 if (count > 0) {
359 notifyListeners();
360 reloadLauncherIfExternal();
361 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800362 return count;
363 }
364
365 @Override
366 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700367 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
369
Chris Wren1ada10d2013-09-13 18:01:38 -0400370 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800371 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
372 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700373 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800374
Sunny Goyald1064182015-08-13 12:08:30 -0700375 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800376 return count;
377 }
378
Sunny Goyal7779d622015-06-11 16:18:39 -0700379 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700380 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700381 if (Binder.getCallingUid() != Process.myUid()) {
382 return null;
383 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700384 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700385
386 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700387 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
388 String extractedColors = extras.getString(
389 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
390 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
391 Utilities.getPrefs(getContext()).edit()
392 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
393 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
394 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700395 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700396 Bundle result = new Bundle();
397 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
398 return result;
399 }
Sunny Goyald2497482015-09-22 18:24:19 -0700400 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
401 clearFlagEmptyDbCreated();
402 return null;
403 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700404 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
405 Bundle result = new Bundle();
406 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
407 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
408 return result;
409 }
Sunny Goyald2497482015-09-22 18:24:19 -0700410 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
411 Bundle result = new Bundle();
412 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
413 return result;
414 }
415 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
416 Bundle result = new Bundle();
417 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
418 return result;
419 }
420 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
421 Bundle result = new Bundle();
422 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
423 return result;
424 }
425 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800426 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700427 return null;
428 }
429 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
430 loadDefaultFavoritesIfNecessary();
431 return null;
432 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700433 }
434 return null;
435 }
436
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700437 /**
438 * Deletes any empty folder from the DB.
439 * @return Ids of deleted folders.
440 */
Sunny Goyald2497482015-09-22 18:24:19 -0700441 private ArrayList<Long> deleteEmptyFolders() {
442 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700443 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
444 db.beginTransaction();
445 try {
446 // Select folders whose id do not match any container value.
447 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
448 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
449 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
450 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700451 + Favorites.TABLE_NAME + ")";
452 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700453 new String[] {LauncherSettings.Favorites._ID},
454 selection, null, null, null, null);
455 while (c.moveToNext()) {
456 folderIds.add(c.getLong(0));
457 }
458 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700459 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700460 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700461 LauncherSettings.Favorites._ID, folderIds), null);
462 }
463 db.setTransactionSuccessful();
464 } catch (SQLException ex) {
465 Log.e(TAG, ex.getMessage(), ex);
466 folderIds.clear();
467 } finally {
468 db.endTransaction();
469 }
470 return folderIds;
471 }
472
Sunny Goyalf076eae2016-01-11 12:25:10 -0800473 /**
474 * Overridden in tests
475 */
476 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700477 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400478 }
479
Adam Cohen091440a2015-03-18 14:16:05 -0700480 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400481 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800482 }
483
Sunny Goyald2497482015-09-22 18:24:19 -0700484 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700485 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700486 }
487
Sunny Goyal42de82f2014-09-26 22:09:29 -0700488 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700489 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700490 * 1) From the app restrictions
491 * 2) From a package provided by play store
492 * 3) From a partner configuration APK, already in the system image
493 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700494 */
Sunny Goyald2497482015-09-22 18:24:19 -0700495 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700496 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700497
Winson Chungc763c4e2013-07-19 13:49:06 -0700498 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500499 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200500
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700501 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
502 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700504 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700505 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700506 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700507 final Partner partner = Partner.get(getContext().getPackageManager());
508 if (partner != null && partner.hasDefaultLayout()) {
509 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700510 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700511 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700512 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700513 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700514 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700515 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700516 }
517 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700518
Sunny Goyal9d219682014-10-23 14:21:02 -0700519 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700520 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700521 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700522 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800523
524 // There might be some partially restored DB items, due to buggy restore logic in
525 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800526 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700527 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700528 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
529 && usingExternallyProvidedLayout) {
530 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800531 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700532 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700533 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700534 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700535 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700536 }
537 }
538
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700539 /**
540 * Creates workspace loader from an XML resource listed in the app restrictions.
541 *
542 * @return the loader if the restrictions are set and the resource exists; null otherwise.
543 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700544 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700545 Context ctx = getContext();
546 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
547 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700548 if (bundle == null) {
549 return null;
550 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700551
Sunny Goyal35ca8732015-04-06 10:45:31 -0700552 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700553 if (packageName != null) {
554 try {
555 Resources targetResources = ctx.getPackageManager()
556 .getResourcesForApplication(packageName);
557 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700558 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700559 } catch (NameNotFoundException e) {
560 Log.e(TAG, "Target package for restricted profile not found", e);
561 return null;
562 }
563 }
564 return null;
565 }
566
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700567 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800568 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700569 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700570 mOpenHelper, getContext().getResources(), defaultLayout);
571 }
572
Sunny Goyald3849d12015-10-29 10:28:32 -0700573 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800574 * The class is subclassed in tests to create an in-memory db.
575 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700576 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700577 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 private long mMaxItemId = -1;
580 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800581
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700582 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
583 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700584 // Table creation sometimes fails silently, which leads to a crash loop.
585 // This way, we will try to create a table every time after crash, so the device
586 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700587 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700588 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
589 // This operation is a no-op if the table already exists.
590 addFavoritesTable(getWritableDatabase(), true);
591 addWorkspacesTable(getWritableDatabase(), true);
592 }
593
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700594 initIds();
595 }
596
597 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700598 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700599 */
600 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700601 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700602 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
603 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700604 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700605 }
606
607 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700608 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
609 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700610 if (mMaxItemId == -1) {
611 mMaxItemId = initializeMaxItemId(getWritableDatabase());
612 }
613 if (mMaxScreenId == -1) {
614 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700615 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
617
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 private boolean tableExists(String tableName) {
619 Cursor c = getReadableDatabase().query(
620 true, "sqlite_master", new String[] {"tbl_name"},
621 "tbl_name = ?", new String[] {tableName},
622 null, null, null, null, null);
623 try {
624 return c.getCount() > 0;
625 } finally {
626 c.close();
627 }
628 }
629
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 @Override
631 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800632 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700633
Adam Cohendcd297f2013-06-18 13:13:40 -0700634 mMaxItemId = 1;
635 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700636
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700637 addFavoritesTable(db, false);
638 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800640 // Fresh and clean launcher DB.
641 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800642 onEmptyDbCreated();
643 }
644
645 /**
646 * Overriden in tests.
647 */
648 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700649 // Database was just created, so wipe any previous widgets
650 if (mWidgetHostResetHandler != null) {
651 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700652 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530653 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700654 }
655
Sunny Goyalf076eae2016-01-11 12:25:10 -0800656 // Set the flag for empty DB
657 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700658
659 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800660 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800661 mContext);
662 }
663
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700664 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800665 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800666 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 }
668
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700669 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700670 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700671 }
672
673 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
674 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700675 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800676 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400677 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
678 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700679 ");");
680 }
681
Adam Cohen119285e2014-04-02 16:59:08 -0700682 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700683 // Delete items directly on the workspace who's screen id doesn't exist
684 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
685 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700686 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700687 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700688 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700689 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700690 " AND " +
691 LauncherSettings.Favorites.CONTAINER + " = " +
692 LauncherSettings.Favorites.CONTAINER_DESKTOP;
693 db.execSQL(removeOrphanedDesktopItems);
694
695 // Delete items contained in folders which no longer exist (after above statement)
696 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
697 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700698 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700699 " WHERE " +
700 LauncherSettings.Favorites.CONTAINER + " <> " +
701 LauncherSettings.Favorites.CONTAINER_DESKTOP +
702 " AND "
703 + LauncherSettings.Favorites.CONTAINER + " <> " +
704 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
705 " AND "
706 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700707 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700708 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
709 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
710 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700711 }
712
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713 @Override
714 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700715 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 switch (oldVersion) {
717 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800718 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800719 case 12: {
720 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
721 // to persist workspace screens and their relative order.
722 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700723 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800724 }
725 case 13: {
726 db.beginTransaction();
727 try {
728 // Insert new column for holding widget provider name
729 db.execSQL("ALTER TABLE favorites " +
730 "ADD COLUMN appWidgetProvider TEXT;");
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 14: {
741 db.beginTransaction();
742 try {
743 // Insert new column for holding update timestamp
744 db.execSQL("ALTER TABLE favorites " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
746 db.execSQL("ALTER TABLE workspaceScreens " +
747 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
748 db.setTransactionSuccessful();
749 } catch (SQLException ex) {
750 Log.e(TAG, ex.getMessage(), ex);
751 // Old version remains, which means we wipe old data
752 break;
753 } finally {
754 db.endTransaction();
755 }
756 }
757 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700758 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 // Old version remains, which means we wipe old data
760 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 }
762 }
763 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700764 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800765 }
766 case 17: {
767 // No-op
768 }
769 case 18: {
770 // Due to a data loss bug, some users may have items associated with screen ids
771 // which no longer exist. Since this can cause other problems, and since the user
772 // will never see these items anyway, we use database upgrade as an opportunity to
773 // clean things up.
774 removeOrphanedItems(db);
775 }
776 case 19: {
777 // Add userId column
778 if (!addProfileColumn(db)) {
779 // Old version remains, which means we wipe old data
780 break;
781 }
782 }
783 case 20:
784 if (!updateFolderItemsRank(db, true)) {
785 break;
786 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800787 case 21:
788 // Recreate workspace table with screen id a primary key
789 if (!recreateWorkspaceTable(db)) {
790 break;
791 }
792 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700793 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
794 // Old version remains, which means we wipe old data
795 break;
796 }
797 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700798 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700799 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700800 case 24:
801 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700802 case 25:
803 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700804 case 26:
805 // QSB was moved to the grid. Clear the first row on screen 0.
806 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800807 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700808 break;
809 }
810 case 27: {
Sunny Goyal24bb66a2017-03-21 15:12:01 -0700811 // Remove "profile extra"
812 db.beginTransaction();
813 try {
814 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
815 for (UserHandle user : um.getUserProfiles()) {
816 long serial = um.getSerialNumberForUser(user);
817 String sql = "update favorites set intent = replace(intent, "
818 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
819 db.execSQL(sql);
820 }
821 db.setTransactionSuccessful();
822 } catch (SQLException ex) {
823 Log.e(TAG, ex.getMessage(), ex);
824 // Old version remains, which means we wipe old data
825 break;
826 } finally {
827 db.endTransaction();
828 }
829 }
830 case 28: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800831 // DB Upgraded successfully
832 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400833 }
834 }
835
Sunny Goyala2cc6242015-01-14 14:23:02 -0800836 // DB was not upgraded
837 Log.w(TAG, "Destroying all old data.");
838 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800839 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800840
Adam Cohen9b1d0622014-05-21 19:01:57 -0700841 @Override
842 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
843 // This shouldn't happen -- throw our hands up in the air and start over.
844 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
845 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700846 createEmptyDB(db);
847 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700848
Sunny Goyal42de82f2014-09-26 22:09:29 -0700849 /**
850 * Clears all the data for a fresh start.
851 */
852 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800853 db.beginTransaction();
854 try {
855 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
856 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
857 onCreate(db);
858 db.setTransactionSuccessful();
859 } finally {
860 db.endTransaction();
861 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700862 }
863
Sunny Goyald2f38192015-02-25 10:46:34 -0800864 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700865 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
866 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
867 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700868 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700869 db.beginTransaction();
870 Cursor c = null;
871 SQLiteStatement updateStmt = null;
872
873 try {
874 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700875 long userSerial = getDefaultUserSerial();
876 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700877 Favorites._ID,
878 Favorites.INTENT,
879 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
880 null, null, null, null);
881
882 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
883 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
884
885 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
886 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
887
888 while (c.moveToNext()) {
889 String intentDescription = c.getString(intentIndex);
890 Intent intent;
891 try {
892 intent = Intent.parseUri(intentDescription, 0);
893 } catch (URISyntaxException e) {
894 Log.e(TAG, "Unable to parse intent", e);
895 continue;
896 }
897
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700898 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700899 continue;
900 }
901
902 long id = c.getLong(idIndex);
903 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700904 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700905 }
906 db.setTransactionSuccessful();
907 } catch (SQLException ex) {
908 Log.w(TAG, "Error deduping shortcuts", ex);
909 } finally {
910 db.endTransaction();
911 if (c != null) {
912 c.close();
913 }
914 if (updateStmt != null) {
915 updateStmt.close();
916 }
917 }
918 }
919
920 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800921 * Recreates workspace table and migrates data to the new table.
922 */
923 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
924 db.beginTransaction();
925 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700926 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800927 new String[] {LauncherSettings.WorkspaceScreens._ID},
928 null, null, null, null,
929 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
930 ArrayList<Long> sortedIDs = new ArrayList<Long>();
931 long maxId = 0;
932 try {
933 while (c.moveToNext()) {
934 Long id = c.getLong(0);
935 if (!sortedIDs.contains(id)) {
936 sortedIDs.add(id);
937 maxId = Math.max(maxId, id);
938 }
939 }
940 } finally {
941 c.close();
942 }
943
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700944 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700945 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800946
947 // Add all screen ids back
948 int total = sortedIDs.size();
949 for (int i = 0; i < total; i++) {
950 ContentValues values = new ContentValues();
951 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
952 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
953 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700954 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800955 }
956 db.setTransactionSuccessful();
957 mMaxScreenId = maxId;
958 } catch (SQLException ex) {
959 // Old version remains, which means we wipe old data
960 Log.e(TAG, ex.getMessage(), ex);
961 return false;
962 } finally {
963 db.endTransaction();
964 }
965 return true;
966 }
967
Adam Cohen091440a2015-03-18 14:16:05 -0700968 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800969 db.beginTransaction();
970 try {
971 if (addRankColumn) {
972 // Insert new column for holding rank
973 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
974 }
975
976 // Get a map for folder ID to folder width
977 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
978 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
979 + " GROUP BY container;",
980 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
981
982 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800983 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
984 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800985 new Object[] {c.getLong(1) + 1, c.getLong(0)});
986 }
987
988 c.close();
989 db.setTransactionSuccessful();
990 } catch (SQLException ex) {
991 // Old version remains, which means we wipe old data
992 Log.e(TAG, ex.getMessage(), ex);
993 return false;
994 } finally {
995 db.endTransaction();
996 }
997 return true;
998 }
999
Kenny Guyed131872014-04-30 03:02:21 +01001000 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001001 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -07001002 }
1003
1004 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +01001005 db.beginTransaction();
1006 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001007 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1008 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +01001009 db.setTransactionSuccessful();
1010 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001011 Log.e(TAG, ex.getMessage(), ex);
1012 return false;
1013 } finally {
1014 db.endTransaction();
1015 }
1016 return true;
1017 }
1018
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001019 // Generates a new ID to use for an object in your database. This method should be only
1020 // called from the main UI thread. As an exception, we do call it when we call the
1021 // constructor from the worker thread; however, this doesn't extend until after the
1022 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1023 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001024 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001025 public long generateNewItemId() {
1026 if (mMaxItemId < 0) {
1027 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001028 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001029 mMaxItemId += 1;
1030 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001031 }
1032
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001033 @Override
1034 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001035 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001036 }
1037
Chris Wren5dee7af2013-12-20 17:22:11 -05001038 public void checkId(String table, ContentValues values) {
1039 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001040 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001041 mMaxScreenId = Math.max(id, mMaxScreenId);
1042 } else {
1043 mMaxItemId = Math.max(id, mMaxItemId);
1044 }
1045 }
1046
Adam Cohendcd297f2013-06-18 13:13:40 -07001047 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001048 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 }
1050
1051 // Generates a new ID to use for an workspace screen in your database. This method
1052 // should be only called from the main UI thread. As an exception, we do call it when we
1053 // call the constructor from the worker thread; however, this doesn't extend until after the
1054 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1055 // after that point
1056 public long generateNewScreenId() {
1057 if (mMaxScreenId < 0) {
1058 throw new RuntimeException("Error: max screen id was not initialized");
1059 }
1060 mMaxScreenId += 1;
1061 return mMaxScreenId;
1062 }
1063
Adam Cohendcd297f2013-06-18 13:13:40 -07001064 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001065 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001066 }
1067
Adam Cohen091440a2015-03-18 14:16:05 -07001068 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001069 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001070 // TODO: Use multiple loaders with fall-back and transaction.
1071 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001072
1073 // Add the screens specified by the items above
1074 Collections.sort(screenIds);
1075 int rank = 0;
1076 ContentValues values = new ContentValues();
1077 for (Long id : screenIds) {
1078 values.clear();
1079 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1080 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001081 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001082 throw new RuntimeException("Failed initialize screen table"
1083 + "from default layout");
1084 }
1085 rank++;
1086 }
1087
1088 // Ensure that the max ids are initialized
1089 mMaxItemId = initializeMaxItemId(db);
1090 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001091
Adam Cohen71483f42014-05-15 14:04:01 -07001092 return count;
1093 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001094 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001095
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001096 /**
1097 * @return the max _id in the provided table.
1098 */
Adam Cohen091440a2015-03-18 14:16:05 -07001099 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001100 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1101 // get the result
1102 long id = -1;
1103 if (c != null && c.moveToNext()) {
1104 id = c.getLong(0);
1105 }
1106 if (c != null) {
1107 c.close();
1108 }
1109
1110 if (id == -1) {
1111 throw new RuntimeException("Error: could not query max id in " + table);
1112 }
1113
1114 return id;
1115 }
1116
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001117 static class SqlArguments {
1118 public final String table;
1119 public final String where;
1120 public final String[] args;
1121
1122 SqlArguments(Uri url, String where, String[] args) {
1123 if (url.getPathSegments().size() == 1) {
1124 this.table = url.getPathSegments().get(0);
1125 this.where = where;
1126 this.args = args;
1127 } else if (url.getPathSegments().size() != 2) {
1128 throw new IllegalArgumentException("Invalid URI: " + url);
1129 } else if (!TextUtils.isEmpty(where)) {
1130 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1131 } else {
1132 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001133 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 this.args = null;
1135 }
1136 }
1137
1138 SqlArguments(Uri url) {
1139 if (url.getPathSegments().size() == 1) {
1140 table = url.getPathSegments().get(0);
1141 where = null;
1142 args = null;
1143 } else {
1144 throw new IllegalArgumentException("Invalid URI: " + url);
1145 }
1146 }
1147 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001148
1149 private static class ChangeListenerWrapper implements Handler.Callback {
1150
1151 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1152 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1153 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1154
1155 private LauncherProviderChangeListener mListener;
1156
1157 @Override
1158 public boolean handleMessage(Message msg) {
1159 if (mListener != null) {
1160 switch (msg.what) {
1161 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001162 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001163 break;
1164 case MSG_EXTRACTED_COLORS_CHANGED:
1165 mListener.onExtractedColorsChanged();
1166 break;
1167 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001168 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001169 break;
1170 }
1171 }
1172 return true;
1173 }
1174 }
Adam Cohen72960972014-01-15 18:13:55 -08001175}