blob: d4e3171e519e11f98f554f6097bdb291ed262fcf [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070025import android.content.ContentUris;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000029import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070030import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070031import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070038import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070040import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070041import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070042import android.os.Handler;
43import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070044import android.os.Process;
Sunny Goyale26d1002016-06-20 14:52:14 -070045import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080046import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070050
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
52import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070053import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070055import com.android.launcher3.config.FeatureFlags;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070057import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyalca187462017-03-31 20:09:34 -070058import com.android.launcher3.graphics.IconShapeOverride;
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 Songe295aca2017-02-06 10:46:24 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Sunny Goyal55fddc82017-04-06 15:02:52 -070069import java.lang.reflect.Method;
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;
Sunny Goyal55fddc82017-04-06 15:02:52 -070073import java.util.HashSet;
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 Goyal3c7d55b2017-04-13 12:01:47 -070079 /**
80 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
81 */
82 private static final int SCHEMA_VERSION = 27;
83 /**
84 * Represents the actual data. It could include additional validations and normalizations added
85 * overtime. These must be backwards compatible, else we risk breaking old devices during
86 * restore or binary version downgrade.
87 */
Sunny Goyal55fddc82017-04-06 15:02:52 -070088 private static final int DATA_VERSION = 3;
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070089
90 private static final String PREF_KEY_DATA_VERISON = "provider_data_version";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Sunny Goyale5bb7052015-07-27 14:36:07 -070092 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070093
Sunny Goyale87e6ab2014-11-21 22:42:53 -080094 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070096 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
97
Sunny Goyalb5b55c82016-05-10 12:28:59 -070098 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
99 private Handler mListenerHandler;
100
Sunny Goyalf076eae2016-01-11 12:25:10 -0800101 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102
Hyunyoung Songe295aca2017-02-06 10:46:24 -0800103 /**
104 * $ adb shell dumpsys activity provider com.android.launcher3
105 */
106 @Override
107 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
108 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
109 if (appState == null || !appState.getModel().isModelLoaded()) {
110 return;
111 }
112 appState.getModel().dumpState("", fd, writer, args);
113 }
114
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115 @Override
116 public boolean onCreate() {
Sunny Goyale26d1002016-06-20 14:52:14 -0700117 if (ProviderConfig.IS_DOGFOOD_BUILD) {
118 Log.d(TAG, "Launcher process started");
119 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700120 mListenerHandler = new Handler(mListenerWrapper);
121
Sunny Goyalfdbef272017-02-01 12:52:54 -0800122 // The content provider exists for the entire duration of the launcher main process and
123 // is the first component to get created. Initializing FileLog here ensures that it's
124 // always available in the main process.
125 FileLog.setDir(getContext().getApplicationContext().getFilesDir());
Sunny Goyalca187462017-03-31 20:09:34 -0700126 IconShapeOverride.apply(getContext());
Sunny Goyal3e443a22017-04-10 10:49:01 -0700127 SessionCommitReceiver.applyDefaultUserPrefs(getContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 return true;
129 }
130
Sunny Goyald3849d12015-10-29 10:28:32 -0700131 /**
132 * Sets a provider listener.
133 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700134 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700135 Preconditions.assertUIThread();
136 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700137 }
138
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139 @Override
140 public String getType(Uri uri) {
141 SqlArguments args = new SqlArguments(uri, null, null);
142 if (TextUtils.isEmpty(args.where)) {
143 return "vnd.android.cursor.dir/" + args.table;
144 } else {
145 return "vnd.android.cursor.item/" + args.table;
146 }
147 }
148
Sunny Goyalf076eae2016-01-11 12:25:10 -0800149 /**
150 * Overridden in tests
151 */
152 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700153 if (mOpenHelper == null) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700154 if (LauncherAppState.PROFILE_STARTUP) {
155 Trace.beginSection("Opening workspace DB");
156 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700157 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700158
159 if (RestoreDbTask.isPending(getContext())) {
160 if (!RestoreDbTask.performRestore(mOpenHelper)) {
161 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
162 }
163 // Set is pending to false irrespective of the result, so that it doesn't get
164 // executed again.
165 RestoreDbTask.setPending(getContext(), false);
166 }
Sunny Goyale26d1002016-06-20 14:52:14 -0700167
168 if (LauncherAppState.PROFILE_STARTUP) {
169 Trace.endSection();
170 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700171 }
172 }
173
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 @Override
175 public Cursor query(Uri uri, String[] projection, String selection,
176 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700177 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
179 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
180 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
181 qb.setTables(args.table);
182
Romain Guy73b979d2009-06-09 12:57:21 -0700183 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
185 result.setNotificationUri(getContext().getContentResolver(), uri);
186
187 return result;
188 }
189
Adam Cohen091440a2015-03-18 14:16:05 -0700190 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700191 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500192 if (values == null) {
193 throw new RuntimeException("Error: attempting to insert null values");
194 }
Adam Cohen71483f42014-05-15 14:04:01 -0700195 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700196 throw new RuntimeException("Error: attempting to add item without specifying an id");
197 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500198 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700199 return db.insert(table, nullColumnHack, values);
200 }
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700203 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700204 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
205 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800206 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700207 }
208 }
209 }
210
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 @Override
212 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700213 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214 SqlArguments args = new SqlArguments(uri);
215
Sunny Goyald1064182015-08-13 12:08:30 -0700216 // In very limited cases, we support system|signature permission apps to modify the db.
217 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700218 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700219 return null;
220 }
221 }
222
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400224 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700225 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800226 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227
228 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700229 notifyListeners();
230
Sunny Goyalc74e4192015-09-08 14:01:03 -0700231 if (Utilities.ATLEAST_MARSHMALLOW) {
232 reloadLauncherIfExternal();
233 } else {
234 // Deprecated behavior to support legacy devices which rely on provider callbacks.
235 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
236 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800237 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700238 }
239
240 String notify = uri.getQueryParameter("notify");
241 if (notify == null || "true".equals(notify)) {
242 getContext().getContentResolver().notifyChange(uri, null);
243 }
244 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800245 return uri;
246 }
247
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700248 private boolean initializeExternalAdd(ContentValues values) {
249 // 1. Ensure that externally added items have a valid item id
250 long id = mOpenHelper.generateNewItemId();
251 values.put(LauncherSettings.Favorites._ID, id);
252
253 // 2. In the case of an app widget, and if no app widget id is specified, we
254 // attempt allocate and bind the widget.
255 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
256 if (itemType != null &&
257 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
258 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
259
260 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
261 ComponentName cn = ComponentName.unflattenFromString(
262 values.getAsString(Favorites.APPWIDGET_PROVIDER));
263
264 if (cn != null) {
265 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700266 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
267 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700268 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
269 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700270 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700271 return false;
272 }
273 } catch (RuntimeException e) {
274 Log.e(TAG, "Failed to initialize external widget", e);
275 return false;
276 }
277 } else {
278 return false;
279 }
280 }
281
282 // Add screen id if not present
283 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
284 SQLiteStatement stmp = null;
285 try {
286 stmp = mOpenHelper.getWritableDatabase().compileStatement(
287 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
288 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
289 stmp.bindLong(1, screenId);
290
291 ContentValues valuesInserted = new ContentValues();
292 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
293 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
294 return true;
295 } catch (Exception e) {
296 return false;
297 } finally {
298 Utilities.closeSilently(stmp);
299 }
300 }
301
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 @Override
303 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700304 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305 SqlArguments args = new SqlArguments(uri);
306
307 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
308 db.beginTransaction();
309 try {
310 int numValues = values.length;
311 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700313 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
314 return 0;
315 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800316 }
317 db.setTransactionSuccessful();
318 } finally {
319 db.endTransaction();
320 }
321
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700322 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700323 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 return values.length;
325 }
326
327 @Override
Yura085c8532014-02-11 15:15:29 +0000328 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
329 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700330 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000331 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
332 db.beginTransaction();
333 try {
334 ContentProviderResult[] result = super.applyBatch(operations);
335 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700336 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000337 return result;
338 } finally {
339 db.endTransaction();
340 }
341 }
342
343 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700345 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800346 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
347
348 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349
Louis Begina9c21c62016-08-15 15:18:41 -0700350 if (Binder.getCallingPid() != Process.myPid()
351 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700352 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700353 }
354 int count = db.delete(args.table, args.where, args.args);
355 if (count > 0) {
356 notifyListeners();
357 reloadLauncherIfExternal();
358 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 return count;
360 }
361
362 @Override
363 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700364 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800365 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
366
Chris Wren1ada10d2013-09-13 18:01:38 -0400367 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
369 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700370 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800371
Sunny Goyald1064182015-08-13 12:08:30 -0700372 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800373 return count;
374 }
375
Sunny Goyal7779d622015-06-11 16:18:39 -0700376 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700377 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700378 if (Binder.getCallingUid() != Process.myUid()) {
379 return null;
380 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700381 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700382
383 switch (method) {
Tony Wickham827cef22016-03-17 15:39:39 -0700384 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
385 String extractedColors = extras.getString(
386 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
387 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
388 Utilities.getPrefs(getContext()).edit()
389 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
390 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
391 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700392 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700393 Bundle result = new Bundle();
394 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
395 return result;
396 }
Sunny Goyald2497482015-09-22 18:24:19 -0700397 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
398 clearFlagEmptyDbCreated();
399 return null;
400 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700401 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
402 Bundle result = new Bundle();
403 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
404 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
405 return result;
406 }
Sunny Goyald2497482015-09-22 18:24:19 -0700407 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
408 Bundle result = new Bundle();
409 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
410 return result;
411 }
412 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
413 Bundle result = new Bundle();
414 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
415 return result;
416 }
417 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
418 Bundle result = new Bundle();
419 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
420 return result;
421 }
422 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800423 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700424 return null;
425 }
426 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
427 loadDefaultFavoritesIfNecessary();
428 return null;
429 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700430 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
431 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
432 return null;
433 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700434 }
435 return null;
436 }
437
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700438 /**
439 * Deletes any empty folder from the DB.
440 * @return Ids of deleted folders.
441 */
Sunny Goyald2497482015-09-22 18:24:19 -0700442 private ArrayList<Long> deleteEmptyFolders() {
443 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700444 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
445 db.beginTransaction();
446 try {
447 // Select folders whose id do not match any container value.
448 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
449 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
450 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
451 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700452 + Favorites.TABLE_NAME + ")";
453 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700454 new String[] {LauncherSettings.Favorites._ID},
455 selection, null, null, null, null);
456 while (c.moveToNext()) {
457 folderIds.add(c.getLong(0));
458 }
459 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700460 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700461 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700462 LauncherSettings.Favorites._ID, folderIds), null);
463 }
464 db.setTransactionSuccessful();
465 } catch (SQLException ex) {
466 Log.e(TAG, ex.getMessage(), ex);
467 folderIds.clear();
468 } finally {
469 db.endTransaction();
470 }
471 return folderIds;
472 }
473
Sunny Goyalf076eae2016-01-11 12:25:10 -0800474 /**
475 * Overridden in tests
476 */
477 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700478 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 }
480
Adam Cohen091440a2015-03-18 14:16:05 -0700481 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400482 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800483 }
484
Sunny Goyald2497482015-09-22 18:24:19 -0700485 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700486 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700487 }
488
Sunny Goyal42de82f2014-09-26 22:09:29 -0700489 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700490 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700491 * 1) From the app restrictions
492 * 2) From a package provided by play store
493 * 3) From a partner configuration APK, already in the system image
494 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700495 */
Sunny Goyald2497482015-09-22 18:24:19 -0700496 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700497 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700498
Winson Chungc763c4e2013-07-19 13:49:06 -0700499 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500500 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200501
Sunny Goyal55fddc82017-04-06 15:02:52 -0700502 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700503 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700504 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700506 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700507 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700508 final Partner partner = Partner.get(getContext().getPackageManager());
509 if (partner != null && partner.hasDefaultLayout()) {
510 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700511 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700512 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700513 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700514 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700515 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700516 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700517 }
518 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700519
Sunny Goyal9d219682014-10-23 14:21:02 -0700520 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700521 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700522 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700523 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800524
525 // There might be some partially restored DB items, due to buggy restore logic in
526 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800527 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700528 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700529 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
530 && usingExternallyProvidedLayout) {
531 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800532 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700533 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700535 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700536 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700537 }
538 }
539
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700540 /**
541 * Creates workspace loader from an XML resource listed in the app restrictions.
542 *
543 * @return the loader if the restrictions are set and the resource exists; null otherwise.
544 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700546 Context ctx = getContext();
547 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
548 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700549 if (bundle == null) {
550 return null;
551 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700552
Sunny Goyal35ca8732015-04-06 10:45:31 -0700553 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700554 if (packageName != null) {
555 try {
556 Resources targetResources = ctx.getPackageManager()
557 .getResourcesForApplication(packageName);
558 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700559 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700560 } catch (NameNotFoundException e) {
561 Log.e(TAG, "Target package for restricted profile not found", e);
562 return null;
563 }
564 }
565 return null;
566 }
567
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal87f784c2017-01-11 10:48:34 -0800569 int defaultLayout = LauncherAppState.getIDP(getContext()).defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700570 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700571 mOpenHelper, getContext().getResources(), defaultLayout);
572 }
573
Sunny Goyald3849d12015-10-29 10:28:32 -0700574 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800575 * The class is subclassed in tests to create an in-memory db.
576 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700577 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700578 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800579 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700580 private long mMaxItemId = -1;
581 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700583 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
584 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700585 // Table creation sometimes fails silently, which leads to a crash loop.
586 // This way, we will try to create a table every time after crash, so the device
587 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700588 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700589 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
590 // This operation is a no-op if the table already exists.
591 addFavoritesTable(getWritableDatabase(), true);
592 addWorkspacesTable(getWritableDatabase(), true);
593 }
594
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700595 initIds();
596 }
597
598 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700599 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700600 */
601 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700602 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700603 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700604 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700605 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700606 }
607
608 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700609 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
610 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700611 if (mMaxItemId == -1) {
612 mMaxItemId = initializeMaxItemId(getWritableDatabase());
613 }
614 if (mMaxScreenId == -1) {
615 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700616 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800617 }
618
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700619 private boolean tableExists(String tableName) {
620 Cursor c = getReadableDatabase().query(
621 true, "sqlite_master", new String[] {"tbl_name"},
622 "tbl_name = ?", new String[] {tableName},
623 null, null, null, null, null);
624 try {
625 return c.getCount() > 0;
626 } finally {
627 c.close();
628 }
629 }
630
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631 @Override
632 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800633 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700634
Adam Cohendcd297f2013-06-18 13:13:40 -0700635 mMaxItemId = 1;
636 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700637
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700638 addFavoritesTable(db, false);
639 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800641 // Fresh and clean launcher DB.
642 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800643 onEmptyDbCreated();
644 }
645
646 /**
647 * Overriden in tests.
648 */
649 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700650 // Database was just created, so wipe any previous widgets
651 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700652 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700653 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530654 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700655 }
656
Sunny Goyalf076eae2016-01-11 12:25:10 -0800657 // Set the flag for empty DB
658 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700659
660 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800661 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800662 mContext);
663 }
664
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700665 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800666 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800667 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 }
669
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700670 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700671 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700672 }
673
674 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
675 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700676 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800677 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400678 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
679 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700680 ");");
681 }
682
Adam Cohen119285e2014-04-02 16:59:08 -0700683 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700684 // Delete items directly on the workspace who's screen id doesn't exist
685 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
686 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700687 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700688 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700689 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700690 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700691 " AND " +
692 LauncherSettings.Favorites.CONTAINER + " = " +
693 LauncherSettings.Favorites.CONTAINER_DESKTOP;
694 db.execSQL(removeOrphanedDesktopItems);
695
696 // Delete items contained in folders which no longer exist (after above statement)
697 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
698 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700699 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700700 " WHERE " +
701 LauncherSettings.Favorites.CONTAINER + " <> " +
702 LauncherSettings.Favorites.CONTAINER_DESKTOP +
703 " AND "
704 + LauncherSettings.Favorites.CONTAINER + " <> " +
705 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
706 " AND "
707 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700708 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700709 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
710 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
711 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700712 }
713
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800714 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700715 public void onOpen(SQLiteDatabase db) {
716 super.onOpen(db);
717 SharedPreferences prefs = mContext
718 .getSharedPreferences(LauncherFiles.DEVICE_PREFERENCES_KEY, 0);
719 int oldVersion = prefs.getInt(PREF_KEY_DATA_VERISON, 0);
720 if (oldVersion != DATA_VERSION) {
721 // Only run the data upgrade path for an existing db.
722 if (!Utilities.getPrefs(mContext).getBoolean(EMPTY_DATABASE_CREATED, false)) {
723 db.beginTransaction();
724 try {
725 onDataUpgrade(db, oldVersion);
726 db.setTransactionSuccessful();
727 } catch (Exception e) {
728 Log.d(TAG, "Error updating data version, ignoring", e);
729 return;
730 } finally {
731 db.endTransaction();
732 }
733 }
734 prefs.edit().putInt(PREF_KEY_DATA_VERISON, DATA_VERSION).apply();
735 }
736 }
737
738 /**
739 * Called when the data is updated as part of app update. It can be called multiple times
740 * with old version, even though it had been run before. The changes made here must be
741 * backwards compatible, else we risk breaking old devices during restore or binary
742 * version downgrade.
743 */
744 protected void onDataUpgrade(SQLiteDatabase db, int oldVersion) {
745 switch (oldVersion) {
746 case 0:
747 case 1: {
748 // Remove "profile extra"
749 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
750 for (UserHandle user : um.getUserProfiles()) {
751 long serial = um.getSerialNumberForUser(user);
752 String sql = "update favorites set intent = replace(intent, "
753 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
754 db.execSQL(sql);
755 }
756 }
757 case 2:
Sunny Goyal55fddc82017-04-06 15:02:52 -0700758 removeGhostWidgets(db);
759 case 3:
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700760 // data updated
761 return;
762 }
763 }
764
765 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800766 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700767 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800768 switch (oldVersion) {
769 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800770 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800771 case 12: {
772 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
773 // to persist workspace screens and their relative order.
774 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700775 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800776 }
777 case 13: {
778 db.beginTransaction();
779 try {
780 // Insert new column for holding widget provider name
781 db.execSQL("ALTER TABLE favorites " +
782 "ADD COLUMN appWidgetProvider TEXT;");
783 db.setTransactionSuccessful();
784 } catch (SQLException ex) {
785 Log.e(TAG, ex.getMessage(), ex);
786 // Old version remains, which means we wipe old data
787 break;
788 } finally {
789 db.endTransaction();
790 }
791 }
792 case 14: {
793 db.beginTransaction();
794 try {
795 // Insert new column for holding update timestamp
796 db.execSQL("ALTER TABLE favorites " +
797 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
798 db.execSQL("ALTER TABLE workspaceScreens " +
799 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
800 db.setTransactionSuccessful();
801 } catch (SQLException ex) {
802 Log.e(TAG, ex.getMessage(), ex);
803 // Old version remains, which means we wipe old data
804 break;
805 } finally {
806 db.endTransaction();
807 }
808 }
809 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700810 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800811 // Old version remains, which means we wipe old data
812 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800813 }
814 }
815 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700816 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800817 }
818 case 17: {
819 // No-op
820 }
821 case 18: {
822 // Due to a data loss bug, some users may have items associated with screen ids
823 // which no longer exist. Since this can cause other problems, and since the user
824 // will never see these items anyway, we use database upgrade as an opportunity to
825 // clean things up.
826 removeOrphanedItems(db);
827 }
828 case 19: {
829 // Add userId column
830 if (!addProfileColumn(db)) {
831 // Old version remains, which means we wipe old data
832 break;
833 }
834 }
835 case 20:
836 if (!updateFolderItemsRank(db, true)) {
837 break;
838 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800839 case 21:
840 // Recreate workspace table with screen id a primary key
841 if (!recreateWorkspaceTable(db)) {
842 break;
843 }
844 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700845 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
846 // Old version remains, which means we wipe old data
847 break;
848 }
849 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700850 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700851 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700852 case 24:
853 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700854 case 25:
855 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700856 case 26:
857 // QSB was moved to the grid. Clear the first row on screen 0.
858 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800859 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700860 break;
861 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700862 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800863 // DB Upgraded successfully
864 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400865 }
866
Sunny Goyala2cc6242015-01-14 14:23:02 -0800867 // DB was not upgraded
868 Log.w(TAG, "Destroying all old data.");
869 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800870 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800871
Adam Cohen9b1d0622014-05-21 19:01:57 -0700872 @Override
873 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700874 if (oldVersion == 28 && newVersion == 27) {
875 // TODO: remove this check. This is only applicable for internal development/testing
876 // and for any released version of Launcher.
877 return;
878 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700879 // This shouldn't happen -- throw our hands up in the air and start over.
880 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
881 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700882 createEmptyDB(db);
883 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700884
Sunny Goyal42de82f2014-09-26 22:09:29 -0700885 /**
886 * Clears all the data for a fresh start.
887 */
888 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800889 db.beginTransaction();
890 try {
891 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
892 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
893 onCreate(db);
894 db.setTransactionSuccessful();
895 } finally {
896 db.endTransaction();
897 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700898 }
899
Sunny Goyald2f38192015-02-25 10:46:34 -0800900 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700901 * Removes widgets which are registered to the Launcher's host, but are not present
902 * in our model.
903 */
904 public void removeGhostWidgets(SQLiteDatabase db) {
905 // Get all existing widget ids.
906 final AppWidgetHost host = newLauncherWidgetHost();
907 final int[] allWidgets;
908 try {
909 Method getter = AppWidgetHost.class.getDeclaredMethod("getAppWidgetIds");
910 getter.setAccessible(true);
911 allWidgets = (int[]) getter.invoke(host);
912 } catch (Exception e) {
913 Log.e(TAG, "getAppWidgetIds not supported", e);
914 return;
915 }
916 try {
917 Cursor c = db.query(Favorites.TABLE_NAME,
918 new String[] {Favorites.APPWIDGET_ID },
919 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null);
920 HashSet<Integer> validWidgets = new HashSet<>();
921 while (c.moveToNext()) {
922 validWidgets.add(c.getInt(0));
923 }
924 c.close();
925
926 for (int widgetId : allWidgets) {
927 if (!validWidgets.contains(widgetId)) {
928 try {
929 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
930 host.deleteAppWidgetId(widgetId);
931 } catch (RuntimeException e) {
932 // Ignore
933 }
934 }
935 }
936 } catch (SQLException ex) {
937 Log.w(TAG, "Error getting widgets list", ex);
938 }
939 }
940
941 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700942 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
943 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
944 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700945 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700946 db.beginTransaction();
947 Cursor c = null;
948 SQLiteStatement updateStmt = null;
949
950 try {
951 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700952 long userSerial = getDefaultUserSerial();
953 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700954 Favorites._ID,
955 Favorites.INTENT,
956 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
957 null, null, null, null);
958
959 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
960 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
961
962 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
963 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
964
965 while (c.moveToNext()) {
966 String intentDescription = c.getString(intentIndex);
967 Intent intent;
968 try {
969 intent = Intent.parseUri(intentDescription, 0);
970 } catch (URISyntaxException e) {
971 Log.e(TAG, "Unable to parse intent", e);
972 continue;
973 }
974
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700975 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700976 continue;
977 }
978
979 long id = c.getLong(idIndex);
980 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700981 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700982 }
983 db.setTransactionSuccessful();
984 } catch (SQLException ex) {
985 Log.w(TAG, "Error deduping shortcuts", ex);
986 } finally {
987 db.endTransaction();
988 if (c != null) {
989 c.close();
990 }
991 if (updateStmt != null) {
992 updateStmt.close();
993 }
994 }
995 }
996
997 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800998 * Recreates workspace table and migrates data to the new table.
999 */
1000 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
1001 db.beginTransaction();
1002 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001003 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -08001004 new String[] {LauncherSettings.WorkspaceScreens._ID},
1005 null, null, null, null,
1006 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1007 ArrayList<Long> sortedIDs = new ArrayList<Long>();
1008 long maxId = 0;
1009 try {
1010 while (c.moveToNext()) {
1011 Long id = c.getLong(0);
1012 if (!sortedIDs.contains(id)) {
1013 sortedIDs.add(id);
1014 maxId = Math.max(maxId, id);
1015 }
1016 }
1017 } finally {
1018 c.close();
1019 }
1020
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001021 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -07001022 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -08001023
1024 // Add all screen ids back
1025 int total = sortedIDs.size();
1026 for (int i = 0; i < total; i++) {
1027 ContentValues values = new ContentValues();
1028 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
1029 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1030 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001031 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -08001032 }
1033 db.setTransactionSuccessful();
1034 mMaxScreenId = maxId;
1035 } catch (SQLException ex) {
1036 // Old version remains, which means we wipe old data
1037 Log.e(TAG, ex.getMessage(), ex);
1038 return false;
1039 } finally {
1040 db.endTransaction();
1041 }
1042 return true;
1043 }
1044
Adam Cohen091440a2015-03-18 14:16:05 -07001045 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001046 db.beginTransaction();
1047 try {
1048 if (addRankColumn) {
1049 // Insert new column for holding rank
1050 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1051 }
1052
1053 // Get a map for folder ID to folder width
1054 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1055 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1056 + " GROUP BY container;",
1057 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1058
1059 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001060 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1061 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001062 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1063 }
1064
1065 c.close();
1066 db.setTransactionSuccessful();
1067 } catch (SQLException ex) {
1068 // Old version remains, which means we wipe old data
1069 Log.e(TAG, ex.getMessage(), ex);
1070 return false;
1071 } finally {
1072 db.endTransaction();
1073 }
1074 return true;
1075 }
1076
Kenny Guyed131872014-04-30 03:02:21 +01001077 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001078 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -07001079 }
1080
1081 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +01001082 db.beginTransaction();
1083 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001084 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1085 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +01001086 db.setTransactionSuccessful();
1087 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001088 Log.e(TAG, ex.getMessage(), ex);
1089 return false;
1090 } finally {
1091 db.endTransaction();
1092 }
1093 return true;
1094 }
1095
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001096 // Generates a new ID to use for an object in your database. This method should be only
1097 // called from the main UI thread. As an exception, we do call it when we call the
1098 // constructor from the worker thread; however, this doesn't extend until after the
1099 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1100 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001101 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001102 public long generateNewItemId() {
1103 if (mMaxItemId < 0) {
1104 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001105 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001106 mMaxItemId += 1;
1107 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001108 }
1109
Sunny Goyal55fddc82017-04-06 15:02:52 -07001110 public AppWidgetHost newLauncherWidgetHost() {
1111 return new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID);
1112 }
1113
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001114 @Override
1115 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001116 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001117 }
1118
Chris Wren5dee7af2013-12-20 17:22:11 -05001119 public void checkId(String table, ContentValues values) {
1120 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001121 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001122 mMaxScreenId = Math.max(id, mMaxScreenId);
1123 } else {
1124 mMaxItemId = Math.max(id, mMaxItemId);
1125 }
1126 }
1127
Adam Cohendcd297f2013-06-18 13:13:40 -07001128 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001129 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001130 }
1131
1132 // Generates a new ID to use for an workspace screen in your database. This method
1133 // should be only called from the main UI thread. As an exception, we do call it when we
1134 // call the constructor from the worker thread; however, this doesn't extend until after the
1135 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1136 // after that point
1137 public long generateNewScreenId() {
1138 if (mMaxScreenId < 0) {
1139 throw new RuntimeException("Error: max screen id was not initialized");
1140 }
1141 mMaxScreenId += 1;
1142 return mMaxScreenId;
1143 }
1144
Adam Cohendcd297f2013-06-18 13:13:40 -07001145 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001146 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001147 }
1148
Adam Cohen091440a2015-03-18 14:16:05 -07001149 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001150 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001151 // TODO: Use multiple loaders with fall-back and transaction.
1152 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001153
1154 // Add the screens specified by the items above
1155 Collections.sort(screenIds);
1156 int rank = 0;
1157 ContentValues values = new ContentValues();
1158 for (Long id : screenIds) {
1159 values.clear();
1160 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1161 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001162 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001163 throw new RuntimeException("Failed initialize screen table"
1164 + "from default layout");
1165 }
1166 rank++;
1167 }
1168
1169 // Ensure that the max ids are initialized
1170 mMaxItemId = initializeMaxItemId(db);
1171 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001172
Adam Cohen71483f42014-05-15 14:04:01 -07001173 return count;
1174 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001175 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001176
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001177 /**
1178 * @return the max _id in the provided table.
1179 */
Adam Cohen091440a2015-03-18 14:16:05 -07001180 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001181 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1182 // get the result
1183 long id = -1;
1184 if (c != null && c.moveToNext()) {
1185 id = c.getLong(0);
1186 }
1187 if (c != null) {
1188 c.close();
1189 }
1190
1191 if (id == -1) {
1192 throw new RuntimeException("Error: could not query max id in " + table);
1193 }
1194
1195 return id;
1196 }
1197
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001198 static class SqlArguments {
1199 public final String table;
1200 public final String where;
1201 public final String[] args;
1202
1203 SqlArguments(Uri url, String where, String[] args) {
1204 if (url.getPathSegments().size() == 1) {
1205 this.table = url.getPathSegments().get(0);
1206 this.where = where;
1207 this.args = args;
1208 } else if (url.getPathSegments().size() != 2) {
1209 throw new IllegalArgumentException("Invalid URI: " + url);
1210 } else if (!TextUtils.isEmpty(where)) {
1211 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1212 } else {
1213 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001214 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001215 this.args = null;
1216 }
1217 }
1218
1219 SqlArguments(Uri url) {
1220 if (url.getPathSegments().size() == 1) {
1221 table = url.getPathSegments().get(0);
1222 where = null;
1223 args = null;
1224 } else {
1225 throw new IllegalArgumentException("Invalid URI: " + url);
1226 }
1227 }
1228 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001229
1230 private static class ChangeListenerWrapper implements Handler.Callback {
1231
1232 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1233 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1234 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1235
1236 private LauncherProviderChangeListener mListener;
1237
1238 @Override
1239 public boolean handleMessage(Message msg) {
1240 if (mListener != null) {
1241 switch (msg.what) {
1242 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001243 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001244 break;
1245 case MSG_EXTRACTED_COLORS_CHANGED:
1246 mListener.onExtractedColorsChanged();
1247 break;
1248 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001249 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001250 break;
1251 }
1252 }
1253 return true;
1254 }
1255 }
Adam Cohen72960972014-01-15 18:13:55 -08001256}