blob: f0760948075e1d2e2bedf99df73f91eafaa4d16b [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 Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070046import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070047import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050049import android.util.SparseArray;
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;
Kenny Guyed131872014-04-30 03:02:21 +010053import com.android.launcher3.compat.UserHandleCompat;
54import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040055import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070056import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070058import com.android.launcher3.util.NoLocaleSqliteContext;
Adam Cohen091440a2015-03-18 14:16:05 -070059import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070060
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070067 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Sunny Goyale5bb7052015-07-27 14:36:07 -070072 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070073
Sunny Goyal18b640c2015-04-17 09:24:01 -070074 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
75 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080076 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Sunny Goyald3849d12015-10-29 10:28:32 -070080 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070081 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyalf076eae2016-01-11 12:25:10 -080082 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 return true;
88 }
89
Sunny Goyald3849d12015-10-29 10:28:32 -070090 /**
91 * Sets a provider listener.
92 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070093 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070094 synchronized (LISTENER_LOCK) {
95 mListener = listener;
96 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 }
98
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099 @Override
100 public String getType(Uri uri) {
101 SqlArguments args = new SqlArguments(uri, null, null);
102 if (TextUtils.isEmpty(args.where)) {
103 return "vnd.android.cursor.dir/" + args.table;
104 } else {
105 return "vnd.android.cursor.item/" + args.table;
106 }
107 }
108
Sunny Goyalf076eae2016-01-11 12:25:10 -0800109 /**
110 * Overridden in tests
111 */
112 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700113 if (mOpenHelper == null) {
114 mOpenHelper = new DatabaseHelper(getContext(), this);
115 }
116 }
117
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800118 @Override
119 public Cursor query(Uri uri, String[] projection, String selection,
120 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700121 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122
123 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
124 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
125 qb.setTables(args.table);
126
Romain Guy73b979d2009-06-09 12:57:21 -0700127 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
129 result.setNotificationUri(getContext().getContentResolver(), uri);
130
131 return result;
132 }
133
Adam Cohen091440a2015-03-18 14:16:05 -0700134 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500136 if (values == null) {
137 throw new RuntimeException("Error: attempting to insert null values");
138 }
Adam Cohen71483f42014-05-15 14:04:01 -0700139 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 throw new RuntimeException("Error: attempting to add item without specifying an id");
141 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500142 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700143 return db.insert(table, nullColumnHack, values);
144 }
145
Sunny Goyald1064182015-08-13 12:08:30 -0700146 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700147 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700148 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
149 if (app != null) {
150 app.reloadWorkspace();
151 }
152 }
153 }
154
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 @Override
156 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800158 SqlArguments args = new SqlArguments(uri);
159
Sunny Goyald1064182015-08-13 12:08:30 -0700160 // In very limited cases, we support system|signature permission apps to modify the db.
161 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700162 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
163 return null;
164 }
165 }
166
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400168 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700169 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800170 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171
172 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700173 notifyListeners();
174
Sunny Goyalc74e4192015-09-08 14:01:03 -0700175 if (Utilities.ATLEAST_MARSHMALLOW) {
176 reloadLauncherIfExternal();
177 } else {
178 // Deprecated behavior to support legacy devices which rely on provider callbacks.
179 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
180 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
181 app.reloadWorkspace();
182 }
183
184 String notify = uri.getQueryParameter("notify");
185 if (notify == null || "true".equals(notify)) {
186 getContext().getContentResolver().notifyChange(uri, null);
187 }
188 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 return uri;
190 }
191
192 @Override
193 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700194 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 SqlArguments args = new SqlArguments(uri);
196
197 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
198 db.beginTransaction();
199 try {
200 int numValues = values.length;
201 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400202 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700203 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
204 return 0;
205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 }
207 db.setTransactionSuccessful();
208 } finally {
209 db.endTransaction();
210 }
211
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700212 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700213 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214 return values.length;
215 }
216
217 @Override
Yura085c8532014-02-11 15:15:29 +0000218 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
219 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700220 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000221 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
222 db.beginTransaction();
223 try {
224 ContentProviderResult[] result = super.applyBatch(operations);
225 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700226 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000227 return result;
228 } finally {
229 db.endTransaction();
230 }
231 }
232
233 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700235 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
237
238 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
239 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700240 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241
Sunny Goyald1064182015-08-13 12:08:30 -0700242 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800243 return count;
244 }
245
246 @Override
247 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700248 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800249 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
250
Chris Wren1ada10d2013-09-13 18:01:38 -0400251 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800252 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
253 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700254 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800255
Sunny Goyald1064182015-08-13 12:08:30 -0700256 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800257 return count;
258 }
259
Sunny Goyal7779d622015-06-11 16:18:39 -0700260 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700261 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700262 if (Binder.getCallingUid() != Process.myUid()) {
263 return null;
264 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700265 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700266
267 switch (method) {
268 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
269 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800270 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
271 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
272 Utilities.isAllowRotationPrefEnabled(getContext()));
273 } else {
274 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
275 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
276 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
277 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700278 return result;
279 }
280 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
Tony Wickham827cef22016-03-17 15:39:39 -0700281 final boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700282 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Tony Wickham827cef22016-03-17 15:39:39 -0700283 new MainThreadExecutor().execute(new Runnable() {
284 @Override
285 public void run() {
286 synchronized (LISTENER_LOCK) {
287 if (mListener != null) {
288 mListener.onSettingsChanged(arg, value);
289 }
290 }
291
Sunny Goyald3849d12015-10-29 10:28:32 -0700292 }
Tony Wickham827cef22016-03-17 15:39:39 -0700293 });
Sunny Goyalb171e562016-01-21 16:41:54 -0800294 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
295 LauncherBackupAgentHelper.dataChanged(getContext());
296 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700297 Bundle result = new Bundle();
298 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
299 return result;
300 }
Tony Wickham827cef22016-03-17 15:39:39 -0700301 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
302 String extractedColors = extras.getString(
303 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
304 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
305 Utilities.getPrefs(getContext()).edit()
306 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
307 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
308 .apply();
309 new MainThreadExecutor().execute(new Runnable() {
310 @Override
311 public void run() {
312 synchronized (LISTENER_LOCK) {
313 if (mListener != null) {
314 mListener.onExtractedColorsChanged();
315 }
316 }
317
318 }
319 });
320 Bundle result = new Bundle();
321 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
322 return result;
323 }
Sunny Goyald2497482015-09-22 18:24:19 -0700324 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
325 clearFlagEmptyDbCreated();
326 return null;
327 }
328 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
329 Bundle result = new Bundle();
330 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
331 return result;
332 }
333 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
334 Bundle result = new Bundle();
335 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
336 return result;
337 }
338 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
339 Bundle result = new Bundle();
340 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
341 return result;
342 }
343 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
344 createEmptyDB();
345 return null;
346 }
347 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
348 loadDefaultFavoritesIfNecessary();
349 return null;
350 }
351 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
352 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
353 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
354 return null;
355 }
356 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
357 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
358 return null;
359 }
360 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
361 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
362 return null;
363 }
364 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800365 // Are you sure? (y/n)
366 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700367 return null;
368 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700369 }
370 return null;
371 }
372
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700373 /**
374 * Deletes any empty folder from the DB.
375 * @return Ids of deleted folders.
376 */
Sunny Goyald2497482015-09-22 18:24:19 -0700377 private ArrayList<Long> deleteEmptyFolders() {
378 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700379 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
380 db.beginTransaction();
381 try {
382 // Select folders whose id do not match any container value.
383 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
384 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
385 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
386 LauncherSettings.Favorites.CONTAINER + " FROM "
387 + TABLE_FAVORITES + ")";
388 Cursor c = db.query(TABLE_FAVORITES,
389 new String[] {LauncherSettings.Favorites._ID},
390 selection, null, null, null, null);
391 while (c.moveToNext()) {
392 folderIds.add(c.getLong(0));
393 }
394 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700395 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700396 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
397 LauncherSettings.Favorites._ID, folderIds), null);
398 }
399 db.setTransactionSuccessful();
400 } catch (SQLException ex) {
401 Log.e(TAG, ex.getMessage(), ex);
402 folderIds.clear();
403 } finally {
404 db.endTransaction();
405 }
406 return folderIds;
407 }
408
Sunny Goyalf076eae2016-01-11 12:25:10 -0800409 /**
410 * Overridden in tests
411 */
412 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400413 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400414 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700415 synchronized (LISTENER_LOCK) {
416 if (mListener != null) {
417 mListener.onLauncherProviderChange();
418 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700419 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400420 }
421
Adam Cohen091440a2015-03-18 14:16:05 -0700422 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400423 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800424 }
425
Brian Muramatsu5524b492012-10-02 16:55:54 -0700426 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700427 * Clears all the data for a fresh start.
428 */
Sunny Goyald2497482015-09-22 18:24:19 -0700429 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700430 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
431 }
432
Sunny Goyald2497482015-09-22 18:24:19 -0700433 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700434 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700435 }
436
Sunny Goyal42de82f2014-09-26 22:09:29 -0700437 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700438 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700439 * 1) From the app restrictions
440 * 2) From a package provided by play store
441 * 3) From a partner configuration APK, already in the system image
442 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700443 */
Sunny Goyald2497482015-09-22 18:24:19 -0700444 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700445 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700446
Winson Chungc763c4e2013-07-19 13:49:06 -0700447 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500448 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200449
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700450 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
451 if (loader == null) {
452 loader = AutoInstallsLayout.get(getContext(),
453 mOpenHelper.mAppWidgetHost, mOpenHelper);
454 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700455 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700456 final Partner partner = Partner.get(getContext().getPackageManager());
457 if (partner != null && partner.hasDefaultLayout()) {
458 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700459 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700460 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700461 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700462 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
463 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700464 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700465 }
466 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467
Sunny Goyal9d219682014-10-23 14:21:02 -0700468 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700469 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700470 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700471 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800472
473 // There might be some partially restored DB items, due to buggy restore logic in
474 // previous versions of launcher.
475 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700476 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700477 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
478 && usingExternallyProvidedLayout) {
479 // Unable to load external layout. Cleanup and load the internal layout.
480 createEmptyDB();
481 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
482 getDefaultLayoutParser());
483 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700484 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700485 }
486 }
487
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700488 /**
489 * Creates workspace loader from an XML resource listed in the app restrictions.
490 *
491 * @return the loader if the restrictions are set and the resource exists; null otherwise.
492 */
493 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
494 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
495 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700496 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700497 return null;
498 }
499
500 Context ctx = getContext();
501 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
502 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700503 if (bundle == null) {
504 return null;
505 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700506
Sunny Goyal35ca8732015-04-06 10:45:31 -0700507 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700508 if (packageName != null) {
509 try {
510 Resources targetResources = ctx.getPackageManager()
511 .getResourcesForApplication(packageName);
512 return AutoInstallsLayout.get(ctx, packageName, targetResources,
513 mOpenHelper.mAppWidgetHost, mOpenHelper);
514 } catch (NameNotFoundException e) {
515 Log.e(TAG, "Target package for restricted profile not found", e);
516 return null;
517 }
518 }
519 return null;
520 }
521
Sunny Goyal9d219682014-10-23 14:21:02 -0700522 private DefaultLayoutParser getDefaultLayoutParser() {
523 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700524 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700525 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
526 mOpenHelper, getContext().getResources(), defaultLayout);
527 }
528
Sunny Goyald3849d12015-10-29 10:28:32 -0700529 /**
530 * Send notification that we've deleted the {@link AppWidgetHost},
531 * probably as part of the initial database creation. The receiver may
532 * want to re-call {@link AppWidgetHost#startListening()} to ensure
533 * callbacks are correctly set.
534 */
535 @Thunk void notifyAppHostReset() {
536 new MainThreadExecutor().execute(new Runnable() {
537
538 @Override
539 public void run() {
540 synchronized (LISTENER_LOCK) {
541 if (mListener != null) {
542 mListener.onAppWidgetHostReset();
543 }
544 }
545 }
546 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500547 }
548
Sunny Goyalf076eae2016-01-11 12:25:10 -0800549 /**
550 * The class is subclassed in tests to create an in-memory db.
551 */
552 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700553 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800554 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700555 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700556 private long mMaxItemId = -1;
557 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800558
Sunny Goyald3849d12015-10-29 10:28:32 -0700559 DatabaseHelper(Context context, LauncherProvider provider) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700560 this(context, provider, LauncherFiles.LAUNCHER_DB,
561 new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID));
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700562 // Table creation sometimes fails silently, which leads to a crash loop.
563 // This way, we will try to create a table every time after crash, so the device
564 // would eventually be able to recover.
565 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
566 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
567 // This operation is a no-op if the table already exists.
568 addFavoritesTable(getWritableDatabase(), true);
569 addWorkspacesTable(getWritableDatabase(), true);
570 }
571
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 initIds();
573 }
574
575 /**
576 * Constructor used only in tests.
577 */
578 public DatabaseHelper(
579 Context context, LauncherProvider provider, String tableName, AppWidgetHost host) {
580 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
581 mContext = context;
582 mProvider = provider;
583 mAppWidgetHost = host;
584 }
585
586 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700587 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
588 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700589 if (mMaxItemId == -1) {
590 mMaxItemId = initializeMaxItemId(getWritableDatabase());
591 }
592 if (mMaxScreenId == -1) {
593 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700594 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800595 }
596
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700597 private boolean tableExists(String tableName) {
598 Cursor c = getReadableDatabase().query(
599 true, "sqlite_master", new String[] {"tbl_name"},
600 "tbl_name = ?", new String[] {tableName},
601 null, null, null, null, null);
602 try {
603 return c.getCount() > 0;
604 } finally {
605 c.close();
606 }
607 }
608
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609 @Override
610 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800611 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700612
Adam Cohendcd297f2013-06-18 13:13:40 -0700613 mMaxItemId = 1;
614 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700615
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700616 addFavoritesTable(db, false);
617 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800618
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700619 // Database was just created, so wipe any previous widgets
620 if (mAppWidgetHost != null) {
621 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700622 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700624
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800625 // Fresh and clean launcher DB.
626 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800627 onEmptyDbCreated();
628 }
629
630 /**
631 * Overriden in tests.
632 */
633 protected void onEmptyDbCreated() {
634 // Set the flag for empty DB
635 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700636
637 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800638 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
639 mContext);
640 }
641
642 protected long getDefaultUserSerial() {
643 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
644 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 }
646
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700647 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700648 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700649 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
650 "_id INTEGER PRIMARY KEY," +
651 "title TEXT," +
652 "intent TEXT," +
653 "container INTEGER," +
654 "screen INTEGER," +
655 "cellX INTEGER," +
656 "cellY INTEGER," +
657 "spanX INTEGER," +
658 "spanY INTEGER," +
659 "itemType INTEGER," +
660 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
661 "isShortcut INTEGER," +
662 "iconType INTEGER," +
663 "iconPackage TEXT," +
664 "iconResource TEXT," +
665 "icon BLOB," +
666 "uri TEXT," +
667 "displayMode INTEGER," +
668 "appWidgetProvider TEXT," +
669 "modified INTEGER NOT NULL DEFAULT 0," +
670 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800671 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700672 "rank INTEGER NOT NULL DEFAULT 0," +
673 "options INTEGER NOT NULL DEFAULT 0" +
674 ");");
675 }
676
677 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
678 String ifNotExists = optional ? " IF NOT EXISTS " : "";
679 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800680 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400681 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
682 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700683 ");");
684 }
685
Adam Cohen119285e2014-04-02 16:59:08 -0700686 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700687 // Delete items directly on the workspace who's screen id doesn't exist
688 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
689 // AND container = -100"
690 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
691 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700692 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700693 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
694 " AND " +
695 LauncherSettings.Favorites.CONTAINER + " = " +
696 LauncherSettings.Favorites.CONTAINER_DESKTOP;
697 db.execSQL(removeOrphanedDesktopItems);
698
699 // Delete items contained in folders which no longer exist (after above statement)
700 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
701 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
702 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
703 " WHERE " +
704 LauncherSettings.Favorites.CONTAINER + " <> " +
705 LauncherSettings.Favorites.CONTAINER_DESKTOP +
706 " AND "
707 + LauncherSettings.Favorites.CONTAINER + " <> " +
708 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
709 " AND "
710 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
711 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
712 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
713 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
714 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700715 }
716
Winson Chungc763c4e2013-07-19 13:49:06 -0700717 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700718 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700719 }
720
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800721 @Override
722 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700723 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800724 switch (oldVersion) {
725 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800726 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 case 12: {
728 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
729 // to persist workspace screens and their relative order.
730 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700731 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 }
733 case 13: {
734 db.beginTransaction();
735 try {
736 // Insert new column for holding widget provider name
737 db.execSQL("ALTER TABLE favorites " +
738 "ADD COLUMN appWidgetProvider TEXT;");
739 db.setTransactionSuccessful();
740 } catch (SQLException ex) {
741 Log.e(TAG, ex.getMessage(), ex);
742 // Old version remains, which means we wipe old data
743 break;
744 } finally {
745 db.endTransaction();
746 }
747 }
748 case 14: {
749 db.beginTransaction();
750 try {
751 // Insert new column for holding update timestamp
752 db.execSQL("ALTER TABLE favorites " +
753 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
754 db.execSQL("ALTER TABLE workspaceScreens " +
755 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
756 db.setTransactionSuccessful();
757 } catch (SQLException ex) {
758 Log.e(TAG, ex.getMessage(), ex);
759 // Old version remains, which means we wipe old data
760 break;
761 } finally {
762 db.endTransaction();
763 }
764 }
765 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700766 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800767 // Old version remains, which means we wipe old data
768 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800769 }
770 }
771 case 16: {
772 // We use the db version upgrade here to identify users who may not have seen
773 // clings yet (because they weren't available), but for whom the clings are now
774 // available (tablet users). Because one of the possible cling flows (migration)
775 // is very destructive (wipes out workspaces), we want to prevent this from showing
776 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800777 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800778 }
779 case 17: {
780 // No-op
781 }
782 case 18: {
783 // Due to a data loss bug, some users may have items associated with screen ids
784 // which no longer exist. Since this can cause other problems, and since the user
785 // will never see these items anyway, we use database upgrade as an opportunity to
786 // clean things up.
787 removeOrphanedItems(db);
788 }
789 case 19: {
790 // Add userId column
791 if (!addProfileColumn(db)) {
792 // Old version remains, which means we wipe old data
793 break;
794 }
795 }
796 case 20:
797 if (!updateFolderItemsRank(db, true)) {
798 break;
799 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800800 case 21:
801 // Recreate workspace table with screen id a primary key
802 if (!recreateWorkspaceTable(db)) {
803 break;
804 }
805 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700806 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
807 // Old version remains, which means we wipe old data
808 break;
809 }
810 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700811 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700812 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700813 case 24:
814 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700815 case 25:
816 convertShortcutsToLauncherActivities(db);
817 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800818 // DB Upgraded successfully
819 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400820 }
821 }
822
Sunny Goyala2cc6242015-01-14 14:23:02 -0800823 // DB was not upgraded
824 Log.w(TAG, "Destroying all old data.");
825 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800826 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800827
Adam Cohen9b1d0622014-05-21 19:01:57 -0700828 @Override
829 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
830 // This shouldn't happen -- throw our hands up in the air and start over.
831 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
832 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700833 createEmptyDB(db);
834 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700835
Sunny Goyal42de82f2014-09-26 22:09:29 -0700836 /**
837 * Clears all the data for a fresh start.
838 */
839 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700840 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
841 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
842 onCreate(db);
843 }
844
Sunny Goyald2f38192015-02-25 10:46:34 -0800845 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700846 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
847 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
848 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700849 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700850 db.beginTransaction();
851 Cursor c = null;
852 SQLiteStatement updateStmt = null;
853
854 try {
855 // Only consider the primary user as other users can't have a shortcut.
856 long userSerial = UserManagerCompat.getInstance(mContext)
857 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
858 c = db.query(TABLE_FAVORITES, new String[] {
859 Favorites._ID,
860 Favorites.INTENT,
861 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
862 null, null, null, null);
863
864 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
865 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
866
867 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
868 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
869
870 while (c.moveToNext()) {
871 String intentDescription = c.getString(intentIndex);
872 Intent intent;
873 try {
874 intent = Intent.parseUri(intentDescription, 0);
875 } catch (URISyntaxException e) {
876 Log.e(TAG, "Unable to parse intent", e);
877 continue;
878 }
879
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700880 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700881 continue;
882 }
883
884 long id = c.getLong(idIndex);
885 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700886 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700887 }
888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
890 Log.w(TAG, "Error deduping shortcuts", ex);
891 } finally {
892 db.endTransaction();
893 if (c != null) {
894 c.close();
895 }
896 if (updateStmt != null) {
897 updateStmt.close();
898 }
899 }
900 }
901
902 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800903 * Recreates workspace table and migrates data to the new table.
904 */
905 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
906 db.beginTransaction();
907 try {
908 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
909 new String[] {LauncherSettings.WorkspaceScreens._ID},
910 null, null, null, null,
911 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
912 ArrayList<Long> sortedIDs = new ArrayList<Long>();
913 long maxId = 0;
914 try {
915 while (c.moveToNext()) {
916 Long id = c.getLong(0);
917 if (!sortedIDs.contains(id)) {
918 sortedIDs.add(id);
919 maxId = Math.max(maxId, id);
920 }
921 }
922 } finally {
923 c.close();
924 }
925
926 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700927 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800928
929 // Add all screen ids back
930 int total = sortedIDs.size();
931 for (int i = 0; i < total; i++) {
932 ContentValues values = new ContentValues();
933 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
934 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
935 addModifiedTime(values);
936 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
937 }
938 db.setTransactionSuccessful();
939 mMaxScreenId = maxId;
940 } catch (SQLException ex) {
941 // Old version remains, which means we wipe old data
942 Log.e(TAG, ex.getMessage(), ex);
943 return false;
944 } finally {
945 db.endTransaction();
946 }
947 return true;
948 }
949
Adam Cohen091440a2015-03-18 14:16:05 -0700950 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800951 db.beginTransaction();
952 try {
953 if (addRankColumn) {
954 // Insert new column for holding rank
955 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
956 }
957
958 // Get a map for folder ID to folder width
959 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
960 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
961 + " GROUP BY container;",
962 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
963
964 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800965 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
966 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800967 new Object[] {c.getLong(1) + 1, c.getLong(0)});
968 }
969
970 c.close();
971 db.setTransactionSuccessful();
972 } catch (SQLException ex) {
973 // Old version remains, which means we wipe old data
974 Log.e(TAG, ex.getMessage(), ex);
975 return false;
976 } finally {
977 db.endTransaction();
978 }
979 return true;
980 }
981
Kenny Guyed131872014-04-30 03:02:21 +0100982 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700983 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
984 // Default to the serial number of this user, for older
985 // shortcuts.
986 long userSerialNumber = userManager.getSerialNumberForUser(
987 UserHandleCompat.myUserHandle());
988 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
989 }
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) {
1022 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
1023 }
1024
Chris Wren5dee7af2013-12-20 17:22:11 -05001025 public void checkId(String table, ContentValues values) {
1026 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1027 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1028 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 Goyalfe4e4b92015-03-04 10:43:45 -08001035 return getMaxId(db, TABLE_FAVORITES);
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 Goyalfe4e4b92015-03-04 10:43:45 -08001052 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001053 }
1054
Adam Cohen091440a2015-03-18 14:16:05 -07001055 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001056 // 1. Ensure that externally added items have a valid item id
1057 long id = generateNewItemId();
1058 values.put(LauncherSettings.Favorites._ID, id);
1059
1060 // 2. In the case of an app widget, and if no app widget id is specified, we
1061 // attempt allocate and bind the widget.
1062 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1063 if (itemType != null &&
1064 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1065 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1066
1067 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1068 ComponentName cn = ComponentName.unflattenFromString(
1069 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1070
1071 if (cn != null) {
1072 try {
1073 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001074 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001075 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001076 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001077 }
1078 } catch (RuntimeException e) {
1079 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001080 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001081 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001082 } else {
1083 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001084 }
1085 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001086
1087 // Add screen id if not present
1088 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1089 if (!addScreenIdIfNecessary(screenId)) {
1090 return false;
1091 }
Adam Cohena043fa82014-07-23 14:49:38 -07001092 return true;
1093 }
1094
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001095 // Returns true of screen id exists, or if successfully added
1096 private boolean addScreenIdIfNecessary(long screenId) {
1097 if (!hasScreenId(screenId)) {
1098 int rank = getMaxScreenRank() + 1;
1099
1100 ContentValues v = new ContentValues();
1101 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1102 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1103 if (dbInsertAndCheck(this, getWritableDatabase(),
1104 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1105 return false;
1106 }
1107 }
1108 return true;
1109 }
1110
1111 private boolean hasScreenId(long screenId) {
1112 SQLiteDatabase db = getWritableDatabase();
1113 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1114 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1115 if (c != null) {
1116 int count = c.getCount();
1117 c.close();
1118 return count > 0;
1119 } else {
1120 return false;
1121 }
1122 }
1123
1124 private int getMaxScreenRank() {
1125 SQLiteDatabase db = getWritableDatabase();
1126 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1127 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1128
1129 // get the result
1130 final int maxRankIndex = 0;
1131 int rank = -1;
1132 if (c != null && c.moveToNext()) {
1133 rank = c.getInt(maxRankIndex);
1134 }
1135 if (c != null) {
1136 c.close();
1137 }
1138
1139 return rank;
1140 }
1141
Adam Cohen091440a2015-03-18 14:16:05 -07001142 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001143 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001144 // TODO: Use multiple loaders with fall-back and transaction.
1145 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001146
1147 // Add the screens specified by the items above
1148 Collections.sort(screenIds);
1149 int rank = 0;
1150 ContentValues values = new ContentValues();
1151 for (Long id : screenIds) {
1152 values.clear();
1153 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1154 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1155 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1156 throw new RuntimeException("Failed initialize screen table"
1157 + "from default layout");
1158 }
1159 rank++;
1160 }
1161
1162 // Ensure that the max ids are initialized
1163 mMaxItemId = initializeMaxItemId(db);
1164 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001165
Adam Cohen71483f42014-05-15 14:04:01 -07001166 return count;
1167 }
1168
Adam Cohen091440a2015-03-18 14:16:05 -07001169 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001170 final ContentResolver resolver = mContext.getContentResolver();
1171 Cursor c = null;
1172 int count = 0;
1173 int curScreen = 0;
1174
1175 try {
1176 c = resolver.query(uri, null, null, null, "title ASC");
1177 } catch (Exception e) {
1178 // Ignore
1179 }
1180
Dan Sandlerd5024042014-01-09 15:01:33 -05001181 // We already have a favorites database in the old provider
1182 if (c != null) {
1183 try {
1184 if (c.getCount() > 0) {
1185 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1186 final int intentIndex
1187 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1188 final int titleIndex
1189 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1190 final int iconTypeIndex
1191 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1192 final int iconIndex
1193 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1194 final int iconPackageIndex
1195 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1196 final int iconResourceIndex
1197 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1198 final int containerIndex
1199 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1200 final int itemTypeIndex
1201 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1202 final int screenIndex
1203 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1204 final int cellXIndex
1205 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1206 final int cellYIndex
1207 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001208 final int profileIndex
1209 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001210
1211 int i = 0;
1212 int curX = 0;
1213 int curY = 0;
1214
1215 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001216 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1217 final int width = (int) profile.numColumns;
1218 final int height = (int) profile.numRows;
1219 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001220
1221 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1222
Adam Cohen72960972014-01-15 18:13:55 -08001223 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1224 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001225 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001226
1227 while (c.moveToNext()) {
1228 final int itemType = c.getInt(itemTypeIndex);
1229 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1230 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1231 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1232 continue;
1233 }
1234
1235 final int cellX = c.getInt(cellXIndex);
1236 final int cellY = c.getInt(cellYIndex);
1237 final int screen = c.getInt(screenIndex);
1238 int container = c.getInt(containerIndex);
1239 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001240
1241 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1242 UserHandleCompat userHandle;
1243 final long userSerialNumber;
1244 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1245 userSerialNumber = c.getInt(profileIndex);
1246 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1247 } else {
1248 // Default to the serial number of this user, for older
1249 // shortcuts.
1250 userHandle = UserHandleCompat.myUserHandle();
1251 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1252 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001253
1254 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001255 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001256 continue;
1257 }
1258
Dan Sandlerd5024042014-01-09 15:01:33 -05001259 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001260
1261 final Intent intent;
1262 final ComponentName cn;
1263 try {
1264 intent = Intent.parseUri(intentStr, 0);
1265 } catch (URISyntaxException e) {
1266 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001267 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001268 continue;
1269 }
1270
1271 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001272 if (TextUtils.isEmpty(intentStr)) {
1273 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001274 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001275 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001276 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001277 !LauncherModel.isValidPackageActivity(mContext, cn,
1278 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001279 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001280 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001281 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001282 } else if (container ==
1283 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1284 // Dedupe icons directly on the workspace
1285
Adam Cohen556f6132014-01-15 15:18:08 -08001286 // Canonicalize
1287 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001288 // does not, so we clear that out to keep them the same.
1289 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001290 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001291 int flags = intent.getFlags();
1292 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001293 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001294 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001295 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001296 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001297 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001298 } else {
1299 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001300 }
1301 }
1302 }
1303
1304 ContentValues values = new ContentValues(c.getColumnCount());
1305 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1306 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1307 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1308 values.put(LauncherSettings.Favorites.ICON_TYPE,
1309 c.getInt(iconTypeIndex));
1310 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1311 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1312 c.getString(iconPackageIndex));
1313 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1314 c.getString(iconResourceIndex));
1315 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1316 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001317 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001318
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001319 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1320 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001321 }
1322
1323 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1324 // In a folder or in the hotseat, preserve position
1325 values.put(LauncherSettings.Favorites.SCREEN, screen);
1326 values.put(LauncherSettings.Favorites.CELLX, cellX);
1327 values.put(LauncherSettings.Favorites.CELLY, cellY);
1328 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001329 // For items contained directly on one of the workspace screen,
1330 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001331 }
1332
1333 values.put(LauncherSettings.Favorites.CONTAINER, container);
1334
Adam Cohen72960972014-01-15 18:13:55 -08001335 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1336 shortcuts.add(values);
1337 } else {
1338 folders.add(values);
1339 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001340 }
1341
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001342 // Now that we have all the hotseat icons, let's go through them left-right
1343 // and assign valid locations for them in the new hotseat
1344 final int N = hotseat.size();
1345 for (int idx=0; idx<N; idx++) {
1346 int hotseatX = hotseat.keyAt(idx);
1347 ContentValues values = hotseat.valueAt(idx);
1348
Adam Cohen2e6da152015-05-06 11:42:25 -07001349 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001350 // let's drop this in the next available hole in the hotseat
1351 while (++hotseatX < hotseatWidth) {
1352 if (hotseat.get(hotseatX) == null) {
1353 // found a spot! move it here
1354 values.put(LauncherSettings.Favorites.SCREEN,
1355 hotseatX);
1356 break;
1357 }
1358 }
1359 }
1360 if (hotseatX >= hotseatWidth) {
1361 // no room for you in the hotseat? it's off to the desktop with you
1362 values.put(LauncherSettings.Favorites.CONTAINER,
1363 Favorites.CONTAINER_DESKTOP);
1364 }
1365 }
1366
Adam Cohen72960972014-01-15 18:13:55 -08001367 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1368 // Folders first
1369 allItems.addAll(folders);
1370 // Then shortcuts
1371 allItems.addAll(shortcuts);
1372
1373 // Layout all the folders
1374 for (ContentValues values: allItems) {
1375 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1376 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1377 // Hotseat items and folder items have already had their
1378 // location information set. Nothing to be done here.
1379 continue;
1380 }
1381 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1382 values.put(LauncherSettings.Favorites.CELLX, curX);
1383 values.put(LauncherSettings.Favorites.CELLY, curY);
1384 curX = (curX + 1) % width;
1385 if (curX == 0) {
1386 curY = (curY + 1);
1387 }
1388 // Leave the last row of icons blank on every screen
1389 if (curY == height - 1) {
1390 curScreen = (int) generateNewScreenId();
1391 curY = 0;
1392 }
1393 }
1394
1395 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001396 db.beginTransaction();
1397 try {
Adam Cohen72960972014-01-15 18:13:55 -08001398 for (ContentValues row: allItems) {
1399 if (row == null) continue;
1400 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001401 < 0) {
1402 return;
1403 } else {
1404 count++;
1405 }
1406 }
1407 db.setTransactionSuccessful();
1408 } finally {
1409 db.endTransaction();
1410 }
1411 }
1412
1413 db.beginTransaction();
1414 try {
1415 for (i=0; i<=curScreen; i++) {
1416 final ContentValues values = new ContentValues();
1417 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1418 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1419 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1420 < 0) {
1421 return;
1422 }
1423 }
1424 db.setTransactionSuccessful();
1425 } finally {
1426 db.endTransaction();
1427 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001428
1429 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001430 }
1431 } finally {
1432 c.close();
1433 }
1434 }
1435
Sunny Goyala1365452015-10-01 15:46:24 -07001436 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1437 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001438
1439 // ensure that new screens are created to hold these icons
1440 setFlagJustLoadedOldDb();
1441
1442 // Update max IDs; very important since we just grabbed IDs from another database
1443 mMaxItemId = initializeMaxItemId(db);
1444 mMaxScreenId = initializeMaxScreenId(db);
1445 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1446 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001447 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001448
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001449 /**
1450 * @return the max _id in the provided table.
1451 */
Adam Cohen091440a2015-03-18 14:16:05 -07001452 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001453 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1454 // get the result
1455 long id = -1;
1456 if (c != null && c.moveToNext()) {
1457 id = c.getLong(0);
1458 }
1459 if (c != null) {
1460 c.close();
1461 }
1462
1463 if (id == -1) {
1464 throw new RuntimeException("Error: could not query max id in " + table);
1465 }
1466
1467 return id;
1468 }
1469
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001470 static class SqlArguments {
1471 public final String table;
1472 public final String where;
1473 public final String[] args;
1474
1475 SqlArguments(Uri url, String where, String[] args) {
1476 if (url.getPathSegments().size() == 1) {
1477 this.table = url.getPathSegments().get(0);
1478 this.where = where;
1479 this.args = args;
1480 } else if (url.getPathSegments().size() != 2) {
1481 throw new IllegalArgumentException("Invalid URI: " + url);
1482 } else if (!TextUtils.isEmpty(where)) {
1483 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1484 } else {
1485 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001486 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001487 this.args = null;
1488 }
1489 }
1490
1491 SqlArguments(Uri url) {
1492 if (url.getPathSegments().size() == 1) {
1493 table = url.getPathSegments().get(0);
1494 where = null;
1495 args = null;
1496 } else {
1497 throw new IllegalArgumentException("Invalid URI: " + url);
1498 }
1499 }
1500 }
Adam Cohen72960972014-01-15 18:13:55 -08001501}