blob: 8d74e608606077aa621f8ee0dd3906952d704bfd [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070045import android.os.Handler;
46import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Process;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070049import android.provider.BaseColumns;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050052import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070053
Sunny Goyal0fe505b2014-08-06 09:55:36 -070054import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
55import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070056import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010057import com.android.launcher3.compat.UserHandleCompat;
58import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070060import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070061import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070062import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070063import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070065
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070068import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050069import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070072 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080073 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
Sunny Goyal5c97f512015-05-19 16:03:28 -070075 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Sunny Goyale5bb7052015-07-27 14:36:07 -070077 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070078
Sunny Goyale87e6ab2014-11-21 22:42:53 -080079 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070081 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
82
Sunny Goyalb5b55c82016-05-10 12:28:59 -070083 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
84 private Handler mListenerHandler;
85
Sunny Goyalf076eae2016-01-11 12:25:10 -080086 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
88 @Override
89 public boolean onCreate() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -070090 mListenerHandler = new Handler(mListenerWrapper);
91
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093 return true;
94 }
95
Sunny Goyald3849d12015-10-29 10:28:32 -070096 /**
97 * Sets a provider listener.
98 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700100 Preconditions.assertUIThread();
101 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
Sunny Goyalf076eae2016-01-11 12:25:10 -0800114 /**
115 * Overridden in tests
116 */
117 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700118 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700119 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyald3849d12015-10-29 10:28:32 -0700120 }
121 }
122
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 @Override
124 public Cursor query(Uri uri, String[] projection, String selection,
125 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700126 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127
128 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
129 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
130 qb.setTables(args.table);
131
Romain Guy73b979d2009-06-09 12:57:21 -0700132 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
134 result.setNotificationUri(getContext().getContentResolver(), uri);
135
136 return result;
137 }
138
Adam Cohen091440a2015-03-18 14:16:05 -0700139 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500141 if (values == null) {
142 throw new RuntimeException("Error: attempting to insert null values");
143 }
Adam Cohen71483f42014-05-15 14:04:01 -0700144 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 throw new RuntimeException("Error: attempting to add item without specifying an id");
146 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500147 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 return db.insert(table, nullColumnHack, values);
149 }
150
Sunny Goyald1064182015-08-13 12:08:30 -0700151 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700152 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700153 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
154 if (app != null) {
155 app.reloadWorkspace();
156 }
157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700162 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 SqlArguments args = new SqlArguments(uri);
164
Sunny Goyald1064182015-08-13 12:08:30 -0700165 // In very limited cases, we support system|signature permission apps to modify the db.
166 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700167 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700168 return null;
169 }
170 }
171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800175 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700178 notifyListeners();
179
Sunny Goyalc74e4192015-09-08 14:01:03 -0700180 if (Utilities.ATLEAST_MARSHMALLOW) {
181 reloadLauncherIfExternal();
182 } else {
183 // Deprecated behavior to support legacy devices which rely on provider callbacks.
184 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
185 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
186 app.reloadWorkspace();
187 }
188
189 String notify = uri.getQueryParameter("notify");
190 if (notify == null || "true".equals(notify)) {
191 getContext().getContentResolver().notifyChange(uri, null);
192 }
193 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 return uri;
195 }
196
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700197 private boolean initializeExternalAdd(ContentValues values) {
198 // 1. Ensure that externally added items have a valid item id
199 long id = mOpenHelper.generateNewItemId();
200 values.put(LauncherSettings.Favorites._ID, id);
201
202 // 2. In the case of an app widget, and if no app widget id is specified, we
203 // attempt allocate and bind the widget.
204 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
205 if (itemType != null &&
206 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
207 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
208
209 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
210 ComponentName cn = ComponentName.unflattenFromString(
211 values.getAsString(Favorites.APPWIDGET_PROVIDER));
212
213 if (cn != null) {
214 try {
215 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
216 .allocateAppWidgetId();
217 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
218 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
219 return false;
220 }
221 } catch (RuntimeException e) {
222 Log.e(TAG, "Failed to initialize external widget", e);
223 return false;
224 }
225 } else {
226 return false;
227 }
228 }
229
230 // Add screen id if not present
231 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
232 SQLiteStatement stmp = null;
233 try {
234 stmp = mOpenHelper.getWritableDatabase().compileStatement(
235 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
236 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
237 stmp.bindLong(1, screenId);
238
239 ContentValues valuesInserted = new ContentValues();
240 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
241 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
242 return true;
243 } catch (Exception e) {
244 return false;
245 } finally {
246 Utilities.closeSilently(stmp);
247 }
248 }
249
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 @Override
251 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700252 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253 SqlArguments args = new SqlArguments(uri);
254
255 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
256 db.beginTransaction();
257 try {
258 int numValues = values.length;
259 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400260 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700261 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
262 return 0;
263 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 }
265 db.setTransactionSuccessful();
266 } finally {
267 db.endTransaction();
268 }
269
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700270 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700271 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 return values.length;
273 }
274
275 @Override
Yura085c8532014-02-11 15:15:29 +0000276 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
277 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700278 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000279 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
280 db.beginTransaction();
281 try {
282 ContentProviderResult[] result = super.applyBatch(operations);
283 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700284 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000285 return result;
286 } finally {
287 db.endTransaction();
288 }
289 }
290
291 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700293 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
295
296 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
297 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700298 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299
Sunny Goyald1064182015-08-13 12:08:30 -0700300 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 return count;
302 }
303
304 @Override
305 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700306 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
308
Chris Wren1ada10d2013-09-13 18:01:38 -0400309 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
311 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700312 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313
Sunny Goyald1064182015-08-13 12:08:30 -0700314 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 return count;
316 }
317
Sunny Goyal7779d622015-06-11 16:18:39 -0700318 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700319 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700320 if (Binder.getCallingUid() != Process.myUid()) {
321 return null;
322 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700324
325 switch (method) {
326 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
327 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800328 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
329 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
330 Utilities.isAllowRotationPrefEnabled(getContext()));
331 } else {
332 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
333 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
334 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
335 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700336 return result;
337 }
338 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
Tony Wickham827cef22016-03-17 15:39:39 -0700339 final boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700340 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyalb171e562016-01-21 16:41:54 -0800341 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
342 LauncherBackupAgentHelper.dataChanged(getContext());
343 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700344 Bundle result = new Bundle();
345 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
346 return result;
347 }
Tony Wickham827cef22016-03-17 15:39:39 -0700348 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
349 String extractedColors = extras.getString(
350 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
351 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
352 Utilities.getPrefs(getContext()).edit()
353 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
354 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
355 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700356 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700357 Bundle result = new Bundle();
358 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
359 return result;
360 }
Sunny Goyald2497482015-09-22 18:24:19 -0700361 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
362 clearFlagEmptyDbCreated();
363 return null;
364 }
365 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
366 Bundle result = new Bundle();
367 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
368 return result;
369 }
370 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
371 Bundle result = new Bundle();
372 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
373 return result;
374 }
375 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
376 Bundle result = new Bundle();
377 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
378 return result;
379 }
380 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
381 createEmptyDB();
382 return null;
383 }
384 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
385 loadDefaultFavoritesIfNecessary();
386 return null;
387 }
388 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
389 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
390 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700391 Utilities.getPrefs(getContext()).edit().putBoolean(EMPTY_DATABASE_CREATED, false)
392 .commit();
Sunny Goyald2497482015-09-22 18:24:19 -0700393 return null;
394 }
395 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
396 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
397 return null;
398 }
399 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
400 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
401 return null;
402 }
403 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800404 // Are you sure? (y/n)
405 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700406 return null;
407 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700408 }
409 return null;
410 }
411
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700412 /**
413 * Deletes any empty folder from the DB.
414 * @return Ids of deleted folders.
415 */
Sunny Goyald2497482015-09-22 18:24:19 -0700416 private ArrayList<Long> deleteEmptyFolders() {
417 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700418 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
419 db.beginTransaction();
420 try {
421 // Select folders whose id do not match any container value.
422 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
423 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
424 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
425 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700426 + Favorites.TABLE_NAME + ")";
427 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 new String[] {LauncherSettings.Favorites._ID},
429 selection, null, null, null, null);
430 while (c.moveToNext()) {
431 folderIds.add(c.getLong(0));
432 }
433 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700434 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700435 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700436 LauncherSettings.Favorites._ID, folderIds), null);
437 }
438 db.setTransactionSuccessful();
439 } catch (SQLException ex) {
440 Log.e(TAG, ex.getMessage(), ex);
441 folderIds.clear();
442 } finally {
443 db.endTransaction();
444 }
445 return folderIds;
446 }
447
Sunny Goyalf076eae2016-01-11 12:25:10 -0800448 /**
449 * Overridden in tests
450 */
451 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400453 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700454 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400455 }
456
Adam Cohen091440a2015-03-18 14:16:05 -0700457 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400458 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800459 }
460
Brian Muramatsu5524b492012-10-02 16:55:54 -0700461 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700462 * Clears all the data for a fresh start.
463 */
Sunny Goyald2497482015-09-22 18:24:19 -0700464 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700465 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
466 }
467
Sunny Goyald2497482015-09-22 18:24:19 -0700468 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700469 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700470 }
471
Sunny Goyal42de82f2014-09-26 22:09:29 -0700472 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700474 * 1) From the app restrictions
475 * 2) From a package provided by play store
476 * 3) From a partner configuration APK, already in the system image
477 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700478 */
Sunny Goyald2497482015-09-22 18:24:19 -0700479 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700480 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700481
Winson Chungc763c4e2013-07-19 13:49:06 -0700482 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500483 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200484
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700485 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
486 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700487 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700489 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700490 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700491 final Partner partner = Partner.get(getContext().getPackageManager());
492 if (partner != null && partner.hasDefaultLayout()) {
493 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700494 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700495 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700496 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700497 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700498 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700499 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700500 }
501 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502
Sunny Goyal9d219682014-10-23 14:21:02 -0700503 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700504 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700506 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800507
508 // There might be some partially restored DB items, due to buggy restore logic in
509 // previous versions of launcher.
510 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700511 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700512 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
513 && usingExternallyProvidedLayout) {
514 // Unable to load external layout. Cleanup and load the internal layout.
515 createEmptyDB();
516 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700517 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700518 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700519 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700520 }
521 }
522
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700523 /**
524 * Creates workspace loader from an XML resource listed in the app restrictions.
525 *
526 * @return the loader if the restrictions are set and the resource exists; null otherwise.
527 */
528 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700529 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700530 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700531 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700532 return null;
533 }
534
535 Context ctx = getContext();
536 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
537 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700538 if (bundle == null) {
539 return null;
540 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541
Sunny Goyal35ca8732015-04-06 10:45:31 -0700542 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700543 if (packageName != null) {
544 try {
545 Resources targetResources = ctx.getPackageManager()
546 .getResourcesForApplication(packageName);
547 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700549 } catch (NameNotFoundException e) {
550 Log.e(TAG, "Target package for restricted profile not found", e);
551 return null;
552 }
553 }
554 return null;
555 }
556
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700558 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700559 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700560 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700561 mOpenHelper, getContext().getResources(), defaultLayout);
562 }
563
Sunny Goyald3849d12015-10-29 10:28:32 -0700564 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800565 * The class is subclassed in tests to create an in-memory db.
566 */
567 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800569 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 private long mMaxItemId = -1;
571 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700573 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
574 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700575 // Table creation sometimes fails silently, which leads to a crash loop.
576 // This way, we will try to create a table every time after crash, so the device
577 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700578 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700579 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
580 // This operation is a no-op if the table already exists.
581 addFavoritesTable(getWritableDatabase(), true);
582 addWorkspacesTable(getWritableDatabase(), true);
583 }
584
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700585 initIds();
586 }
587
588 /**
589 * Constructor used only in tests.
590 */
591 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700592 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700593 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
594 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700595 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700596 }
597
598 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700599 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
600 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700601 if (mMaxItemId == -1) {
602 mMaxItemId = initializeMaxItemId(getWritableDatabase());
603 }
604 if (mMaxScreenId == -1) {
605 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700606 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700609 private boolean tableExists(String tableName) {
610 Cursor c = getReadableDatabase().query(
611 true, "sqlite_master", new String[] {"tbl_name"},
612 "tbl_name = ?", new String[] {tableName},
613 null, null, null, null, null);
614 try {
615 return c.getCount() > 0;
616 } finally {
617 c.close();
618 }
619 }
620
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 @Override
622 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800623 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700624
Adam Cohendcd297f2013-06-18 13:13:40 -0700625 mMaxItemId = 1;
626 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700627
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700628 addFavoritesTable(db, false);
629 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800631 // Fresh and clean launcher DB.
632 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 onEmptyDbCreated();
634 }
635
636 /**
637 * Overriden in tests.
638 */
639 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700640 // Database was just created, so wipe any previous widgets
641 if (mWidgetHostResetHandler != null) {
642 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
643 mWidgetHostResetHandler.sendEmptyMessage(
644 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
645 }
646
Sunny Goyalf076eae2016-01-11 12:25:10 -0800647 // Set the flag for empty DB
648 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700649
650 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800651 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
652 mContext);
653 }
654
655 protected long getDefaultUserSerial() {
656 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
657 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 }
659
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700660 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700661 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700662 db.execSQL("CREATE TABLE " + ifNotExists + Favorites.TABLE_NAME + " (" +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700663 "_id INTEGER PRIMARY KEY," +
664 "title TEXT," +
665 "intent TEXT," +
666 "container INTEGER," +
667 "screen INTEGER," +
668 "cellX INTEGER," +
669 "cellY INTEGER," +
670 "spanX INTEGER," +
671 "spanY INTEGER," +
672 "itemType INTEGER," +
673 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700674 "iconType INTEGER," +
675 "iconPackage TEXT," +
676 "iconResource TEXT," +
677 "icon BLOB," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700678 "appWidgetProvider TEXT," +
679 "modified INTEGER NOT NULL DEFAULT 0," +
680 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800681 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700682 "rank INTEGER NOT NULL DEFAULT 0," +
683 "options INTEGER NOT NULL DEFAULT 0" +
684 ");");
685 }
686
687 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
688 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700689 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800690 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400691 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
692 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700693 ");");
694 }
695
Adam Cohen119285e2014-04-02 16:59:08 -0700696 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700697 // Delete items directly on the workspace who's screen id doesn't exist
698 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
699 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700700 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700701 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700702 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700703 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700704 " AND " +
705 LauncherSettings.Favorites.CONTAINER + " = " +
706 LauncherSettings.Favorites.CONTAINER_DESKTOP;
707 db.execSQL(removeOrphanedDesktopItems);
708
709 // Delete items contained in folders which no longer exist (after above statement)
710 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
711 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700712 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700713 " WHERE " +
714 LauncherSettings.Favorites.CONTAINER + " <> " +
715 LauncherSettings.Favorites.CONTAINER_DESKTOP +
716 " AND "
717 + LauncherSettings.Favorites.CONTAINER + " <> " +
718 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
719 " AND "
720 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700721 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700722 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
723 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
724 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700725 }
726
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800727 @Override
728 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700729 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800730 switch (oldVersion) {
731 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800732 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 case 12: {
734 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
735 // to persist workspace screens and their relative order.
736 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700737 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 }
739 case 13: {
740 db.beginTransaction();
741 try {
742 // Insert new column for holding widget provider name
743 db.execSQL("ALTER TABLE favorites " +
744 "ADD COLUMN appWidgetProvider TEXT;");
745 db.setTransactionSuccessful();
746 } catch (SQLException ex) {
747 Log.e(TAG, ex.getMessage(), ex);
748 // Old version remains, which means we wipe old data
749 break;
750 } finally {
751 db.endTransaction();
752 }
753 }
754 case 14: {
755 db.beginTransaction();
756 try {
757 // Insert new column for holding update timestamp
758 db.execSQL("ALTER TABLE favorites " +
759 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
760 db.execSQL("ALTER TABLE workspaceScreens " +
761 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
762 db.setTransactionSuccessful();
763 } catch (SQLException ex) {
764 Log.e(TAG, ex.getMessage(), ex);
765 // Old version remains, which means we wipe old data
766 break;
767 } finally {
768 db.endTransaction();
769 }
770 }
771 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700772 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800773 // Old version remains, which means we wipe old data
774 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800775 }
776 }
777 case 16: {
778 // We use the db version upgrade here to identify users who may not have seen
779 // clings yet (because they weren't available), but for whom the clings are now
780 // available (tablet users). Because one of the possible cling flows (migration)
781 // is very destructive (wipes out workspaces), we want to prevent this from showing
782 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800783 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800784 }
785 case 17: {
786 // No-op
787 }
788 case 18: {
789 // Due to a data loss bug, some users may have items associated with screen ids
790 // which no longer exist. Since this can cause other problems, and since the user
791 // will never see these items anyway, we use database upgrade as an opportunity to
792 // clean things up.
793 removeOrphanedItems(db);
794 }
795 case 19: {
796 // Add userId column
797 if (!addProfileColumn(db)) {
798 // Old version remains, which means we wipe old data
799 break;
800 }
801 }
802 case 20:
803 if (!updateFolderItemsRank(db, true)) {
804 break;
805 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800806 case 21:
807 // Recreate workspace table with screen id a primary key
808 if (!recreateWorkspaceTable(db)) {
809 break;
810 }
811 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700812 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
813 // Old version remains, which means we wipe old data
814 break;
815 }
816 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700817 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700818 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700819 case 24:
820 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700821 case 25:
822 convertShortcutsToLauncherActivities(db);
823 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 // DB Upgraded successfully
825 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400826 }
827 }
828
Sunny Goyala2cc6242015-01-14 14:23:02 -0800829 // DB was not upgraded
830 Log.w(TAG, "Destroying all old data.");
831 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800832 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800833
Adam Cohen9b1d0622014-05-21 19:01:57 -0700834 @Override
835 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
836 // This shouldn't happen -- throw our hands up in the air and start over.
837 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
838 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700839 createEmptyDB(db);
840 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700841
Sunny Goyal42de82f2014-09-26 22:09:29 -0700842 /**
843 * Clears all the data for a fresh start.
844 */
845 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700846 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
847 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700848 onCreate(db);
849 }
850
Sunny Goyald2f38192015-02-25 10:46:34 -0800851 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
853 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
854 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700855 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700856 db.beginTransaction();
857 Cursor c = null;
858 SQLiteStatement updateStmt = null;
859
860 try {
861 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700862 long userSerial = getDefaultUserSerial();
863 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700864 Favorites._ID,
865 Favorites.INTENT,
866 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
867 null, null, null, null);
868
869 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
870 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
871
872 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
873 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
874
875 while (c.moveToNext()) {
876 String intentDescription = c.getString(intentIndex);
877 Intent intent;
878 try {
879 intent = Intent.parseUri(intentDescription, 0);
880 } catch (URISyntaxException e) {
881 Log.e(TAG, "Unable to parse intent", e);
882 continue;
883 }
884
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700885 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700886 continue;
887 }
888
889 long id = c.getLong(idIndex);
890 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700891 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700892 }
893 db.setTransactionSuccessful();
894 } catch (SQLException ex) {
895 Log.w(TAG, "Error deduping shortcuts", ex);
896 } finally {
897 db.endTransaction();
898 if (c != null) {
899 c.close();
900 }
901 if (updateStmt != null) {
902 updateStmt.close();
903 }
904 }
905 }
906
907 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800908 * Recreates workspace table and migrates data to the new table.
909 */
910 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
911 db.beginTransaction();
912 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700913 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800914 new String[] {LauncherSettings.WorkspaceScreens._ID},
915 null, null, null, null,
916 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
917 ArrayList<Long> sortedIDs = new ArrayList<Long>();
918 long maxId = 0;
919 try {
920 while (c.moveToNext()) {
921 Long id = c.getLong(0);
922 if (!sortedIDs.contains(id)) {
923 sortedIDs.add(id);
924 maxId = Math.max(maxId, id);
925 }
926 }
927 } finally {
928 c.close();
929 }
930
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700931 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700932 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800933
934 // Add all screen ids back
935 int total = sortedIDs.size();
936 for (int i = 0; i < total; i++) {
937 ContentValues values = new ContentValues();
938 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
939 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
940 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700941 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800942 }
943 db.setTransactionSuccessful();
944 mMaxScreenId = maxId;
945 } catch (SQLException ex) {
946 // Old version remains, which means we wipe old data
947 Log.e(TAG, ex.getMessage(), ex);
948 return false;
949 } finally {
950 db.endTransaction();
951 }
952 return true;
953 }
954
Adam Cohen091440a2015-03-18 14:16:05 -0700955 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800956 db.beginTransaction();
957 try {
958 if (addRankColumn) {
959 // Insert new column for holding rank
960 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
961 }
962
963 // Get a map for folder ID to folder width
964 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
965 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
966 + " GROUP BY container;",
967 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
968
969 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800970 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
971 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800972 new Object[] {c.getLong(1) + 1, c.getLong(0)});
973 }
974
975 c.close();
976 db.setTransactionSuccessful();
977 } catch (SQLException ex) {
978 // Old version remains, which means we wipe old data
979 Log.e(TAG, ex.getMessage(), ex);
980 return false;
981 } finally {
982 db.endTransaction();
983 }
984 return true;
985 }
986
Kenny Guyed131872014-04-30 03:02:21 +0100987 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700988 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700989 }
990
991 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100992 db.beginTransaction();
993 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700994 db.execSQL("ALTER TABLE favorites ADD COLUMN "
995 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100996 db.setTransactionSuccessful();
997 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100998 Log.e(TAG, ex.getMessage(), ex);
999 return false;
1000 } finally {
1001 db.endTransaction();
1002 }
1003 return true;
1004 }
1005
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 // Generates a new ID to use for an object in your database. This method should be only
1007 // called from the main UI thread. As an exception, we do call it when we call the
1008 // constructor from the worker thread; however, this doesn't extend until after the
1009 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1010 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001011 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 public long generateNewItemId() {
1013 if (mMaxItemId < 0) {
1014 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 mMaxItemId += 1;
1017 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001018 }
1019
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001020 @Override
1021 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001022 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001023 }
1024
Chris Wren5dee7af2013-12-20 17:22:11 -05001025 public void checkId(String table, ContentValues values) {
1026 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001027 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001028 mMaxScreenId = Math.max(id, mMaxScreenId);
1029 } else {
1030 mMaxItemId = Math.max(id, mMaxItemId);
1031 }
1032 }
1033
Adam Cohendcd297f2013-06-18 13:13:40 -07001034 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001035 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001036 }
1037
1038 // Generates a new ID to use for an workspace screen in your database. This method
1039 // should be only called from the main UI thread. As an exception, we do call it when we
1040 // call the constructor from the worker thread; however, this doesn't extend until after the
1041 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1042 // after that point
1043 public long generateNewScreenId() {
1044 if (mMaxScreenId < 0) {
1045 throw new RuntimeException("Error: max screen id was not initialized");
1046 }
1047 mMaxScreenId += 1;
1048 return mMaxScreenId;
1049 }
1050
Adam Cohendcd297f2013-06-18 13:13:40 -07001051 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001052 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001053 }
1054
Adam Cohen091440a2015-03-18 14:16:05 -07001055 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001056 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001057 // TODO: Use multiple loaders with fall-back and transaction.
1058 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001059
1060 // Add the screens specified by the items above
1061 Collections.sort(screenIds);
1062 int rank = 0;
1063 ContentValues values = new ContentValues();
1064 for (Long id : screenIds) {
1065 values.clear();
1066 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1067 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001068 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001069 throw new RuntimeException("Failed initialize screen table"
1070 + "from default layout");
1071 }
1072 rank++;
1073 }
1074
1075 // Ensure that the max ids are initialized
1076 mMaxItemId = initializeMaxItemId(db);
1077 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001078
Adam Cohen71483f42014-05-15 14:04:01 -07001079 return count;
1080 }
1081
Adam Cohen091440a2015-03-18 14:16:05 -07001082 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001083 final ContentResolver resolver = mContext.getContentResolver();
1084 Cursor c = null;
1085 int count = 0;
1086 int curScreen = 0;
1087
1088 try {
1089 c = resolver.query(uri, null, null, null, "title ASC");
1090 } catch (Exception e) {
1091 // Ignore
1092 }
1093
Dan Sandlerd5024042014-01-09 15:01:33 -05001094 // We already have a favorites database in the old provider
1095 if (c != null) {
1096 try {
1097 if (c.getCount() > 0) {
1098 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1099 final int intentIndex
1100 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1101 final int titleIndex
1102 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1103 final int iconTypeIndex
1104 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1105 final int iconIndex
1106 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1107 final int iconPackageIndex
1108 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1109 final int iconResourceIndex
1110 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1111 final int containerIndex
1112 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1113 final int itemTypeIndex
1114 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1115 final int screenIndex
1116 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1117 final int cellXIndex
1118 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1119 final int cellYIndex
1120 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001121 final int profileIndex
1122 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001123
1124 int i = 0;
1125 int curX = 0;
1126 int curY = 0;
1127
1128 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001129 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1130 final int width = (int) profile.numColumns;
1131 final int height = (int) profile.numRows;
1132 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001133
1134 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1135
Adam Cohen72960972014-01-15 18:13:55 -08001136 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1137 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001138 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001139
1140 while (c.moveToNext()) {
1141 final int itemType = c.getInt(itemTypeIndex);
1142 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1143 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1144 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1145 continue;
1146 }
1147
1148 final int cellX = c.getInt(cellXIndex);
1149 final int cellY = c.getInt(cellYIndex);
1150 final int screen = c.getInt(screenIndex);
1151 int container = c.getInt(containerIndex);
1152 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001153
1154 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1155 UserHandleCompat userHandle;
1156 final long userSerialNumber;
1157 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1158 userSerialNumber = c.getInt(profileIndex);
1159 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1160 } else {
1161 // Default to the serial number of this user, for older
1162 // shortcuts.
1163 userHandle = UserHandleCompat.myUserHandle();
1164 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1165 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001166
1167 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001168 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001169 continue;
1170 }
1171
Dan Sandlerd5024042014-01-09 15:01:33 -05001172 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001173
1174 final Intent intent;
1175 final ComponentName cn;
1176 try {
1177 intent = Intent.parseUri(intentStr, 0);
1178 } catch (URISyntaxException e) {
1179 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001180 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001181 continue;
1182 }
1183
1184 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001185 if (TextUtils.isEmpty(intentStr)) {
1186 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001187 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001188 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001189 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001190 !LauncherModel.isValidPackageActivity(mContext, cn,
1191 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001192 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001193 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001194 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001195 } else if (container ==
1196 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1197 // Dedupe icons directly on the workspace
1198
Adam Cohen556f6132014-01-15 15:18:08 -08001199 // Canonicalize
1200 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001201 // does not, so we clear that out to keep them the same.
1202 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001203 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001204 int flags = intent.getFlags();
1205 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001206 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001207 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001208 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001209 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001210 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001211 } else {
1212 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001213 }
1214 }
1215 }
1216
1217 ContentValues values = new ContentValues(c.getColumnCount());
1218 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1219 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1220 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1221 values.put(LauncherSettings.Favorites.ICON_TYPE,
1222 c.getInt(iconTypeIndex));
1223 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1224 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1225 c.getString(iconPackageIndex));
1226 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1227 c.getString(iconResourceIndex));
1228 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1229 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001230 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001231
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001232 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1233 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001234 }
1235
1236 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1237 // In a folder or in the hotseat, preserve position
1238 values.put(LauncherSettings.Favorites.SCREEN, screen);
1239 values.put(LauncherSettings.Favorites.CELLX, cellX);
1240 values.put(LauncherSettings.Favorites.CELLY, cellY);
1241 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001242 // For items contained directly on one of the workspace screen,
1243 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001244 }
1245
1246 values.put(LauncherSettings.Favorites.CONTAINER, container);
1247
Adam Cohen72960972014-01-15 18:13:55 -08001248 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1249 shortcuts.add(values);
1250 } else {
1251 folders.add(values);
1252 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001253 }
1254
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001255 // Now that we have all the hotseat icons, let's go through them left-right
1256 // and assign valid locations for them in the new hotseat
1257 final int N = hotseat.size();
1258 for (int idx=0; idx<N; idx++) {
1259 int hotseatX = hotseat.keyAt(idx);
1260 ContentValues values = hotseat.valueAt(idx);
1261
Adam Cohen2e6da152015-05-06 11:42:25 -07001262 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001263 // let's drop this in the next available hole in the hotseat
1264 while (++hotseatX < hotseatWidth) {
1265 if (hotseat.get(hotseatX) == null) {
1266 // found a spot! move it here
1267 values.put(LauncherSettings.Favorites.SCREEN,
1268 hotseatX);
1269 break;
1270 }
1271 }
1272 }
1273 if (hotseatX >= hotseatWidth) {
1274 // no room for you in the hotseat? it's off to the desktop with you
1275 values.put(LauncherSettings.Favorites.CONTAINER,
1276 Favorites.CONTAINER_DESKTOP);
1277 }
1278 }
1279
Adam Cohen72960972014-01-15 18:13:55 -08001280 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1281 // Folders first
1282 allItems.addAll(folders);
1283 // Then shortcuts
1284 allItems.addAll(shortcuts);
1285
1286 // Layout all the folders
1287 for (ContentValues values: allItems) {
1288 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1289 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1290 // Hotseat items and folder items have already had their
1291 // location information set. Nothing to be done here.
1292 continue;
1293 }
1294 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1295 values.put(LauncherSettings.Favorites.CELLX, curX);
1296 values.put(LauncherSettings.Favorites.CELLY, curY);
1297 curX = (curX + 1) % width;
1298 if (curX == 0) {
1299 curY = (curY + 1);
1300 }
1301 // Leave the last row of icons blank on every screen
1302 if (curY == height - 1) {
1303 curScreen = (int) generateNewScreenId();
1304 curY = 0;
1305 }
1306 }
1307
1308 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001309 db.beginTransaction();
1310 try {
Adam Cohen72960972014-01-15 18:13:55 -08001311 for (ContentValues row: allItems) {
1312 if (row == null) continue;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001313 if (dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001314 < 0) {
1315 return;
1316 } else {
1317 count++;
1318 }
1319 }
1320 db.setTransactionSuccessful();
1321 } finally {
1322 db.endTransaction();
1323 }
1324 }
1325
1326 db.beginTransaction();
1327 try {
1328 for (i=0; i<=curScreen; i++) {
1329 final ContentValues values = new ContentValues();
1330 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1331 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001332 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values)
Dan Sandlerd5024042014-01-09 15:01:33 -05001333 < 0) {
1334 return;
1335 }
1336 }
1337 db.setTransactionSuccessful();
1338 } finally {
1339 db.endTransaction();
1340 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001341
1342 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001343 }
1344 } finally {
1345 c.close();
1346 }
1347 }
1348
Sunny Goyala1365452015-10-01 15:46:24 -07001349 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1350 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001351
Dan Sandlerd5024042014-01-09 15:01:33 -05001352 // Update max IDs; very important since we just grabbed IDs from another database
1353 mMaxItemId = initializeMaxItemId(db);
1354 mMaxScreenId = initializeMaxScreenId(db);
1355 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1356 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001357 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001358
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001359 /**
1360 * @return the max _id in the provided table.
1361 */
Adam Cohen091440a2015-03-18 14:16:05 -07001362 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001363 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1364 // get the result
1365 long id = -1;
1366 if (c != null && c.moveToNext()) {
1367 id = c.getLong(0);
1368 }
1369 if (c != null) {
1370 c.close();
1371 }
1372
1373 if (id == -1) {
1374 throw new RuntimeException("Error: could not query max id in " + table);
1375 }
1376
1377 return id;
1378 }
1379
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001380 static class SqlArguments {
1381 public final String table;
1382 public final String where;
1383 public final String[] args;
1384
1385 SqlArguments(Uri url, String where, String[] args) {
1386 if (url.getPathSegments().size() == 1) {
1387 this.table = url.getPathSegments().get(0);
1388 this.where = where;
1389 this.args = args;
1390 } else if (url.getPathSegments().size() != 2) {
1391 throw new IllegalArgumentException("Invalid URI: " + url);
1392 } else if (!TextUtils.isEmpty(where)) {
1393 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1394 } else {
1395 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001396 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001397 this.args = null;
1398 }
1399 }
1400
1401 SqlArguments(Uri url) {
1402 if (url.getPathSegments().size() == 1) {
1403 table = url.getPathSegments().get(0);
1404 where = null;
1405 args = null;
1406 } else {
1407 throw new IllegalArgumentException("Invalid URI: " + url);
1408 }
1409 }
1410 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001411
1412 private static class ChangeListenerWrapper implements Handler.Callback {
1413
1414 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1415 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1416 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1417
1418 private LauncherProviderChangeListener mListener;
1419
1420 @Override
1421 public boolean handleMessage(Message msg) {
1422 if (mListener != null) {
1423 switch (msg.what) {
1424 case MSG_LAUNCHER_PROVIDER_CHANGED:
1425 mListener.onLauncherProviderChange();
1426 break;
1427 case MSG_EXTRACTED_COLORS_CHANGED:
1428 mListener.onExtractedColorsChanged();
1429 break;
1430 case MSG_APP_WIDGET_HOST_RESET:
1431 mListener.onAppWidgetHostReset();
1432 break;
1433 }
1434 }
1435 return true;
1436 }
1437 }
Adam Cohen72960972014-01-15 18:13:55 -08001438}