blob: e6d71810771945ca7206a6d0fd78648b8c129466 [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 Song6aa37292017-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 Goyalfdbef272017-02-01 12:52:54 -080059import com.android.launcher3.logging.FileLog;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070063import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Hyunyoung Song6aa37292017-02-06 10:46:24 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070069import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070070import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070071import java.util.Collections;
Louis Begina9c21c62016-08-15 15:18:41 -070072import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070075 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080076 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070078 private static final int DATABASE_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyale5bb7052015-07-27 14:36:07 -070080 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070081
Sunny Goyale87e6ab2014-11-21 22:42:53 -080082 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070084 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
85
Sunny Goyalb5b55c82016-05-10 12:28:59 -070086 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
87 private Handler mListenerHandler;
88
Sunny Goyalf076eae2016-01-11 12:25:10 -080089 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Hyunyoung Song6aa37292017-02-06 10:46:24 -080091 /**
92 * $ adb shell dumpsys activity provider com.android.launcher3
93 */
94 @Override
95 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
96 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
97 if (appState == null || !appState.getModel().isModelLoaded()) {
98 return;
99 }
100 appState.getModel().dumpState("", fd, writer, args);
101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public boolean onCreate() {
Sunny Goyale26d1002016-06-20 14:52:14 -0700105 if (ProviderConfig.IS_DOGFOOD_BUILD) {
106 Log.d(TAG, "Launcher process started");
107 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700108 mListenerHandler = new Handler(mListenerWrapper);
109
Sunny Goyalfdbef272017-02-01 12:52:54 -0800110 // The content provider exists for the entire duration of the launcher main process and
111 // is the first component to get created. Initializing FileLog here ensures that it's
112 // always available in the main process.
113 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114 return true;
115 }
116
Sunny Goyald3849d12015-10-29 10:28:32 -0700117 /**
118 * Sets a provider listener.
119 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700120 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700121 Preconditions.assertUIThread();
122 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700123 }
124
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 @Override
126 public String getType(Uri uri) {
127 SqlArguments args = new SqlArguments(uri, null, null);
128 if (TextUtils.isEmpty(args.where)) {
129 return "vnd.android.cursor.dir/" + args.table;
130 } else {
131 return "vnd.android.cursor.item/" + args.table;
132 }
133 }
134
Sunny Goyalf076eae2016-01-11 12:25:10 -0800135 /**
136 * Overridden in tests
137 */
138 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700139 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700140 if (LauncherAppState.PROFILE_STARTUP) {
141 Trace.beginSection("Opening workspace DB");
142 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700143 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700144
145 if (RestoreDbTask.isPending(getContext())) {
146 if (!RestoreDbTask.performRestore(mOpenHelper)) {
147 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
148 }
149 // Set is pending to false irrespective of the result, so that it doesn't get
150 // executed again.
151 RestoreDbTask.setPending(getContext(), false);
152 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700153
154 if (LauncherAppState.PROFILE_STARTUP) {
155 Trace.endSection();
156 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Cursor query(Uri uri, String[] projection, String selection,
162 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
166 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
167 qb.setTables(args.table);
168
Romain Guy73b979d2009-06-09 12:57:21 -0700169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
171 result.setNotificationUri(getContext().getContentResolver(), uri);
172
173 return result;
174 }
175
Adam Cohen091440a2015-03-18 14:16:05 -0700176 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500178 if (values == null) {
179 throw new RuntimeException("Error: attempting to insert null values");
180 }
Adam Cohen71483f42014-05-15 14:04:01 -0700181 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 throw new RuntimeException("Error: attempting to add item without specifying an id");
183 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500184 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700185 return db.insert(table, nullColumnHack, values);
186 }
187
Sunny Goyald1064182015-08-13 12:08:30 -0700188 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700189 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700190 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
191 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800192 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700193 }
194 }
195 }
196
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 @Override
198 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700199 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 SqlArguments args = new SqlArguments(uri);
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 // In very limited cases, we support system|signature permission apps to modify the db.
203 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700204 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700205 return null;
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700211 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800212 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
214 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700215 notifyListeners();
216
Sunny Goyalc74e4192015-09-08 14:01:03 -0700217 if (Utilities.ATLEAST_MARSHMALLOW) {
218 reloadLauncherIfExternal();
219 } else {
220 // Deprecated behavior to support legacy devices which rely on provider callbacks.
221 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
222 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800223 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700224 }
225
226 String notify = uri.getQueryParameter("notify");
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
230 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 return uri;
232 }
233
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700234 private boolean initializeExternalAdd(ContentValues values) {
235 // 1. Ensure that externally added items have a valid item id
236 long id = mOpenHelper.generateNewItemId();
237 values.put(LauncherSettings.Favorites._ID, id);
238
239 // 2. In the case of an app widget, and if no app widget id is specified, we
240 // attempt allocate and bind the widget.
241 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
242 if (itemType != null &&
243 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
244 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
245
246 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
247 ComponentName cn = ComponentName.unflattenFromString(
248 values.getAsString(Favorites.APPWIDGET_PROVIDER));
249
250 if (cn != null) {
251 try {
252 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
253 .allocateAppWidgetId();
254 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
255 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
256 return false;
257 }
258 } catch (RuntimeException e) {
259 Log.e(TAG, "Failed to initialize external widget", e);
260 return false;
261 }
262 } else {
263 return false;
264 }
265 }
266
267 // Add screen id if not present
268 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
269 SQLiteStatement stmp = null;
270 try {
271 stmp = mOpenHelper.getWritableDatabase().compileStatement(
272 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
273 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
274 stmp.bindLong(1, screenId);
275
276 ContentValues valuesInserted = new ContentValues();
277 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
278 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
279 return true;
280 } catch (Exception e) {
281 return false;
282 } finally {
283 Utilities.closeSilently(stmp);
284 }
285 }
286
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 @Override
288 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700289 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 SqlArguments args = new SqlArguments(uri);
291
292 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
293 db.beginTransaction();
294 try {
295 int numValues = values.length;
296 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400297 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700298 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
299 return 0;
300 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 }
302 db.setTransactionSuccessful();
303 } finally {
304 db.endTransaction();
305 }
306
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700307 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700308 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800309 return values.length;
310 }
311
312 @Override
Yura085c8532014-02-11 15:15:29 +0000313 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
314 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700315 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000316 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
317 db.beginTransaction();
318 try {
319 ContentProviderResult[] result = super.applyBatch(operations);
320 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700321 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000322 return result;
323 } finally {
324 db.endTransaction();
325 }
326 }
327
328 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700330 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
332
333 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334
Louis Begina9c21c62016-08-15 15:18:41 -0700335 if (Binder.getCallingPid() != Process.myPid()
336 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
337 String widgetSelection = TextUtils.isEmpty(args.where) ? "1=1" : args.where;
338 widgetSelection = String.format(Locale.ENGLISH, "%1$s = %2$d AND ( %3$s )",
339 Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET, widgetSelection);
340 try (Cursor c = db.query(Favorites.TABLE_NAME, new String[] { Favorites.APPWIDGET_ID },
341 widgetSelection, args.args, null, null, null)) {
342 AppWidgetHost host = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
343 while (c.moveToNext()) {
344 int widgetId = c.getInt(0);
345 if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
346 try {
347 host.deleteAppWidgetId(widgetId);
348 } catch (RuntimeException e) {
349 Log.e(TAG, "Error deleting widget id " + widgetId, e);
350 }
351 }
352 }
353 }
354 }
355 int count = db.delete(args.table, args.where, args.args);
356 if (count > 0) {
357 notifyListeners();
358 reloadLauncherIfExternal();
359 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 return count;
361 }
362
363 @Override
364 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700365 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800366 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
367
Chris Wren1ada10d2013-09-13 18:01:38 -0400368 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800369 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
370 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700371 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800372
Sunny Goyald1064182015-08-13 12:08:30 -0700373 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800374 return count;
375 }
376
Sunny Goyal7779d622015-06-11 16:18:39 -0700377 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700378 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700379 if (Binder.getCallingUid() != Process.myUid()) {
380 return null;
381 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700382 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700383
384 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700385 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
386 String extractedColors = extras.getString(
387 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
388 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
389 Utilities.getPrefs(getContext()).edit()
390 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
391 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
392 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700393 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700394 Bundle result = new Bundle();
395 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
396 return result;
397 }
Sunny Goyald2497482015-09-22 18:24:19 -0700398 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
399 clearFlagEmptyDbCreated();
400 return null;
401 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700402 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
403 Bundle result = new Bundle();
404 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
405 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
406 return result;
407 }
Sunny Goyald2497482015-09-22 18:24:19 -0700408 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
409 Bundle result = new Bundle();
410 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
411 return result;
412 }
413 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
414 Bundle result = new Bundle();
415 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
416 return result;
417 }
418 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
419 Bundle result = new Bundle();
420 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
421 return result;
422 }
423 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800424 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700425 return null;
426 }
427 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
428 loadDefaultFavoritesIfNecessary();
429 return null;
430 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700431 }
432 return null;
433 }
434
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700435 /**
436 * Deletes any empty folder from the DB.
437 * @return Ids of deleted folders.
438 */
Sunny Goyald2497482015-09-22 18:24:19 -0700439 private ArrayList<Long> deleteEmptyFolders() {
440 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700441 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
442 db.beginTransaction();
443 try {
444 // Select folders whose id do not match any container value.
445 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
446 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
447 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
448 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700449 + Favorites.TABLE_NAME + ")";
450 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700451 new String[] {LauncherSettings.Favorites._ID},
452 selection, null, null, null, null);
453 while (c.moveToNext()) {
454 folderIds.add(c.getLong(0));
455 }
456 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700457 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700458 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700459 LauncherSettings.Favorites._ID, folderIds), null);
460 }
461 db.setTransactionSuccessful();
462 } catch (SQLException ex) {
463 Log.e(TAG, ex.getMessage(), ex);
464 folderIds.clear();
465 } finally {
466 db.endTransaction();
467 }
468 return folderIds;
469 }
470
Sunny Goyalf076eae2016-01-11 12:25:10 -0800471 /**
472 * Overridden in tests
473 */
474 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700475 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 }
477
Adam Cohen091440a2015-03-18 14:16:05 -0700478 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800480 }
481
Sunny Goyald2497482015-09-22 18:24:19 -0700482 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700483 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700484 }
485
Sunny Goyal42de82f2014-09-26 22:09:29 -0700486 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700487 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700488 * 1) From the app restrictions
489 * 2) From a package provided by play store
490 * 3) From a partner configuration APK, already in the system image
491 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700492 */
Sunny Goyald2497482015-09-22 18:24:19 -0700493 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700494 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700495
Winson Chungc763c4e2013-07-19 13:49:06 -0700496 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500497 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200498
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700499 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
500 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700501 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700502 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700504 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700505 final Partner partner = Partner.get(getContext().getPackageManager());
506 if (partner != null && partner.hasDefaultLayout()) {
507 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700508 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700509 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700510 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700511 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700512 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700513 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700514 }
515 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700516
Sunny Goyal9d219682014-10-23 14:21:02 -0700517 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700518 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700520 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800521
522 // There might be some partially restored DB items, due to buggy restore logic in
523 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800524 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700525 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700526 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
527 && usingExternallyProvidedLayout) {
528 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800529 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700530 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700531 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700532 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700533 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700534 }
535 }
536
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700537 /**
538 * Creates workspace loader from an XML resource listed in the app restrictions.
539 *
540 * @return the loader if the restrictions are set and the resource exists; null otherwise.
541 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700542 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700543 Context ctx = getContext();
544 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
545 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700546 if (bundle == null) {
547 return null;
548 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700549
Sunny Goyal35ca8732015-04-06 10:45:31 -0700550 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700551 if (packageName != null) {
552 try {
553 Resources targetResources = ctx.getPackageManager()
554 .getResourcesForApplication(packageName);
555 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700556 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700557 } catch (NameNotFoundException e) {
558 Log.e(TAG, "Target package for restricted profile not found", e);
559 return null;
560 }
561 }
562 return null;
563 }
564
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700565 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800566 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700567 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700568 mOpenHelper, getContext().getResources(), defaultLayout);
569 }
570
Sunny Goyald3849d12015-10-29 10:28:32 -0700571 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800572 * The class is subclassed in tests to create an in-memory db.
573 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700574 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700575 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700577 private long mMaxItemId = -1;
578 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800579
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700580 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
581 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700582 // Table creation sometimes fails silently, which leads to a crash loop.
583 // This way, we will try to create a table every time after crash, so the device
584 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700585 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
587 // This operation is a no-op if the table already exists.
588 addFavoritesTable(getWritableDatabase(), true);
589 addWorkspacesTable(getWritableDatabase(), true);
590 }
591
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700592 initIds();
593 }
594
595 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700596 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700597 */
598 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700599 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700600 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
601 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700602 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700603 }
604
605 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700606 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
607 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700608 if (mMaxItemId == -1) {
609 mMaxItemId = initializeMaxItemId(getWritableDatabase());
610 }
611 if (mMaxScreenId == -1) {
612 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700613 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 }
615
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700616 private boolean tableExists(String tableName) {
617 Cursor c = getReadableDatabase().query(
618 true, "sqlite_master", new String[] {"tbl_name"},
619 "tbl_name = ?", new String[] {tableName},
620 null, null, null, null, null);
621 try {
622 return c.getCount() > 0;
623 } finally {
624 c.close();
625 }
626 }
627
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 @Override
629 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800630 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700631
Adam Cohendcd297f2013-06-18 13:13:40 -0700632 mMaxItemId = 1;
633 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700634
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700635 addFavoritesTable(db, false);
636 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800638 // Fresh and clean launcher DB.
639 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800640 onEmptyDbCreated();
641 }
642
643 /**
644 * Overriden in tests.
645 */
646 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700647 // Database was just created, so wipe any previous widgets
648 if (mWidgetHostResetHandler != null) {
649 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700650 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530651 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700652 }
653
Sunny Goyalf076eae2016-01-11 12:25:10 -0800654 // Set the flag for empty DB
655 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700656
657 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800658 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800659 mContext);
660 }
661
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700662 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800663 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800664 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800665 }
666
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700667 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700668 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700669 }
670
671 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
672 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700673 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800674 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400675 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
676 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700677 ");");
678 }
679
Adam Cohen119285e2014-04-02 16:59:08 -0700680 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700681 // Delete items directly on the workspace who's screen id doesn't exist
682 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
683 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700684 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700685 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700686 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700687 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700688 " AND " +
689 LauncherSettings.Favorites.CONTAINER + " = " +
690 LauncherSettings.Favorites.CONTAINER_DESKTOP;
691 db.execSQL(removeOrphanedDesktopItems);
692
693 // Delete items contained in folders which no longer exist (after above statement)
694 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
695 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700696 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700697 " WHERE " +
698 LauncherSettings.Favorites.CONTAINER + " <> " +
699 LauncherSettings.Favorites.CONTAINER_DESKTOP +
700 " AND "
701 + LauncherSettings.Favorites.CONTAINER + " <> " +
702 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
703 " AND "
704 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700705 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700706 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
707 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
708 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700709 }
710
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800711 @Override
712 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700713 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800714 switch (oldVersion) {
715 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800716 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800717 case 12: {
718 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
719 // to persist workspace screens and their relative order.
720 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700721 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800722 }
723 case 13: {
724 db.beginTransaction();
725 try {
726 // Insert new column for holding widget provider name
727 db.execSQL("ALTER TABLE favorites " +
728 "ADD COLUMN appWidgetProvider TEXT;");
729 db.setTransactionSuccessful();
730 } catch (SQLException ex) {
731 Log.e(TAG, ex.getMessage(), ex);
732 // Old version remains, which means we wipe old data
733 break;
734 } finally {
735 db.endTransaction();
736 }
737 }
738 case 14: {
739 db.beginTransaction();
740 try {
741 // Insert new column for holding update timestamp
742 db.execSQL("ALTER TABLE favorites " +
743 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
744 db.execSQL("ALTER TABLE workspaceScreens " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
746 db.setTransactionSuccessful();
747 } catch (SQLException ex) {
748 Log.e(TAG, ex.getMessage(), ex);
749 // Old version remains, which means we wipe old data
750 break;
751 } finally {
752 db.endTransaction();
753 }
754 }
755 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700756 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 // Old version remains, which means we wipe old data
758 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 }
760 }
761 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700762 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800763 }
764 case 17: {
765 // No-op
766 }
767 case 18: {
768 // Due to a data loss bug, some users may have items associated with screen ids
769 // which no longer exist. Since this can cause other problems, and since the user
770 // will never see these items anyway, we use database upgrade as an opportunity to
771 // clean things up.
772 removeOrphanedItems(db);
773 }
774 case 19: {
775 // Add userId column
776 if (!addProfileColumn(db)) {
777 // Old version remains, which means we wipe old data
778 break;
779 }
780 }
781 case 20:
782 if (!updateFolderItemsRank(db, true)) {
783 break;
784 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800785 case 21:
786 // Recreate workspace table with screen id a primary key
787 if (!recreateWorkspaceTable(db)) {
788 break;
789 }
790 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700791 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
792 // Old version remains, which means we wipe old data
793 break;
794 }
795 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700796 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700797 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700798 case 24:
799 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700800 case 25:
801 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700802 case 26:
803 // QSB was moved to the grid. Clear the first row on screen 0.
804 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800805 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700806 break;
807 }
808 case 27: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800809 // DB Upgraded successfully
810 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400811 }
812 }
813
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 // DB was not upgraded
815 Log.w(TAG, "Destroying all old data.");
816 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800817 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800818
Adam Cohen9b1d0622014-05-21 19:01:57 -0700819 @Override
820 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
821 // This shouldn't happen -- throw our hands up in the air and start over.
822 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
823 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700824 createEmptyDB(db);
825 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700826
Sunny Goyal42de82f2014-09-26 22:09:29 -0700827 /**
828 * Clears all the data for a fresh start.
829 */
830 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800831 db.beginTransaction();
832 try {
833 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
834 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
835 onCreate(db);
836 db.setTransactionSuccessful();
837 } finally {
838 db.endTransaction();
839 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700840 }
841
Sunny Goyald2f38192015-02-25 10:46:34 -0800842 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
844 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
845 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700846 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700847 db.beginTransaction();
848 Cursor c = null;
849 SQLiteStatement updateStmt = null;
850
851 try {
852 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700853 long userSerial = getDefaultUserSerial();
854 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700855 Favorites._ID,
856 Favorites.INTENT,
857 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
858 null, null, null, null);
859
860 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
861 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
862
863 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
864 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
865
866 while (c.moveToNext()) {
867 String intentDescription = c.getString(intentIndex);
868 Intent intent;
869 try {
870 intent = Intent.parseUri(intentDescription, 0);
871 } catch (URISyntaxException e) {
872 Log.e(TAG, "Unable to parse intent", e);
873 continue;
874 }
875
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700876 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700877 continue;
878 }
879
880 long id = c.getLong(idIndex);
881 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700882 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700883 }
884 db.setTransactionSuccessful();
885 } catch (SQLException ex) {
886 Log.w(TAG, "Error deduping shortcuts", ex);
887 } finally {
888 db.endTransaction();
889 if (c != null) {
890 c.close();
891 }
892 if (updateStmt != null) {
893 updateStmt.close();
894 }
895 }
896 }
897
898 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800899 * Recreates workspace table and migrates data to the new table.
900 */
901 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
902 db.beginTransaction();
903 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700904 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800905 new String[] {LauncherSettings.WorkspaceScreens._ID},
906 null, null, null, null,
907 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
908 ArrayList<Long> sortedIDs = new ArrayList<Long>();
909 long maxId = 0;
910 try {
911 while (c.moveToNext()) {
912 Long id = c.getLong(0);
913 if (!sortedIDs.contains(id)) {
914 sortedIDs.add(id);
915 maxId = Math.max(maxId, id);
916 }
917 }
918 } finally {
919 c.close();
920 }
921
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700922 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700923 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800924
925 // Add all screen ids back
926 int total = sortedIDs.size();
927 for (int i = 0; i < total; i++) {
928 ContentValues values = new ContentValues();
929 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
930 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
931 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700932 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800933 }
934 db.setTransactionSuccessful();
935 mMaxScreenId = maxId;
936 } catch (SQLException ex) {
937 // Old version remains, which means we wipe old data
938 Log.e(TAG, ex.getMessage(), ex);
939 return false;
940 } finally {
941 db.endTransaction();
942 }
943 return true;
944 }
945
Adam Cohen091440a2015-03-18 14:16:05 -0700946 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800947 db.beginTransaction();
948 try {
949 if (addRankColumn) {
950 // Insert new column for holding rank
951 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
952 }
953
954 // Get a map for folder ID to folder width
955 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
956 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
957 + " GROUP BY container;",
958 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
959
960 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800961 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
962 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800963 new Object[] {c.getLong(1) + 1, c.getLong(0)});
964 }
965
966 c.close();
967 db.setTransactionSuccessful();
968 } catch (SQLException ex) {
969 // Old version remains, which means we wipe old data
970 Log.e(TAG, ex.getMessage(), ex);
971 return false;
972 } finally {
973 db.endTransaction();
974 }
975 return true;
976 }
977
Kenny Guyed131872014-04-30 03:02:21 +0100978 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700979 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700980 }
981
982 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100983 db.beginTransaction();
984 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700985 db.execSQL("ALTER TABLE favorites ADD COLUMN "
986 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100987 db.setTransactionSuccessful();
988 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100989 Log.e(TAG, ex.getMessage(), ex);
990 return false;
991 } finally {
992 db.endTransaction();
993 }
994 return true;
995 }
996
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700997 // Generates a new ID to use for an object in your database. This method should be only
998 // called from the main UI thread. As an exception, we do call it when we call the
999 // constructor from the worker thread; however, this doesn't extend until after the
1000 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1001 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001002 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 public long generateNewItemId() {
1004 if (mMaxItemId < 0) {
1005 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 mMaxItemId += 1;
1008 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001009 }
1010
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001011 @Override
1012 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001013 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001014 }
1015
Chris Wren5dee7af2013-12-20 17:22:11 -05001016 public void checkId(String table, ContentValues values) {
1017 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001018 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001019 mMaxScreenId = Math.max(id, mMaxScreenId);
1020 } else {
1021 mMaxItemId = Math.max(id, mMaxItemId);
1022 }
1023 }
1024
Adam Cohendcd297f2013-06-18 13:13:40 -07001025 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001026 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001027 }
1028
1029 // Generates a new ID to use for an workspace screen in your database. This method
1030 // should be only called from the main UI thread. As an exception, we do call it when we
1031 // call the constructor from the worker thread; however, this doesn't extend until after the
1032 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1033 // after that point
1034 public long generateNewScreenId() {
1035 if (mMaxScreenId < 0) {
1036 throw new RuntimeException("Error: max screen id was not initialized");
1037 }
1038 mMaxScreenId += 1;
1039 return mMaxScreenId;
1040 }
1041
Adam Cohendcd297f2013-06-18 13:13:40 -07001042 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001043 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001044 }
1045
Adam Cohen091440a2015-03-18 14:16:05 -07001046 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001047 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001048 // TODO: Use multiple loaders with fall-back and transaction.
1049 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001050
1051 // Add the screens specified by the items above
1052 Collections.sort(screenIds);
1053 int rank = 0;
1054 ContentValues values = new ContentValues();
1055 for (Long id : screenIds) {
1056 values.clear();
1057 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1058 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001059 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001060 throw new RuntimeException("Failed initialize screen table"
1061 + "from default layout");
1062 }
1063 rank++;
1064 }
1065
1066 // Ensure that the max ids are initialized
1067 mMaxItemId = initializeMaxItemId(db);
1068 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001069
Adam Cohen71483f42014-05-15 14:04:01 -07001070 return count;
1071 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001072 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001073
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001074 /**
1075 * @return the max _id in the provided table.
1076 */
Adam Cohen091440a2015-03-18 14:16:05 -07001077 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001078 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1079 // get the result
1080 long id = -1;
1081 if (c != null && c.moveToNext()) {
1082 id = c.getLong(0);
1083 }
1084 if (c != null) {
1085 c.close();
1086 }
1087
1088 if (id == -1) {
1089 throw new RuntimeException("Error: could not query max id in " + table);
1090 }
1091
1092 return id;
1093 }
1094
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001095 static class SqlArguments {
1096 public final String table;
1097 public final String where;
1098 public final String[] args;
1099
1100 SqlArguments(Uri url, String where, String[] args) {
1101 if (url.getPathSegments().size() == 1) {
1102 this.table = url.getPathSegments().get(0);
1103 this.where = where;
1104 this.args = args;
1105 } else if (url.getPathSegments().size() != 2) {
1106 throw new IllegalArgumentException("Invalid URI: " + url);
1107 } else if (!TextUtils.isEmpty(where)) {
1108 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1109 } else {
1110 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001111 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001112 this.args = null;
1113 }
1114 }
1115
1116 SqlArguments(Uri url) {
1117 if (url.getPathSegments().size() == 1) {
1118 table = url.getPathSegments().get(0);
1119 where = null;
1120 args = null;
1121 } else {
1122 throw new IllegalArgumentException("Invalid URI: " + url);
1123 }
1124 }
1125 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001126
1127 private static class ChangeListenerWrapper implements Handler.Callback {
1128
1129 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1130 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1131 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1132
1133 private LauncherProviderChangeListener mListener;
1134
1135 @Override
1136 public boolean handleMessage(Message msg) {
1137 if (mListener != null) {
1138 switch (msg.what) {
1139 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001140 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001141 break;
1142 case MSG_EXTRACTED_COLORS_CHANGED:
1143 mListener.onExtractedColorsChanged();
1144 break;
1145 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001146 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001147 break;
1148 }
1149 }
1150 return true;
1151 }
1152 }
Adam Cohen72960972014-01-15 18:13:55 -08001153}