blob: 207121b2747f1c66dfb07b382c493416d8313b40 [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;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070056import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070057import com.android.launcher3.util.NoLocaleSqliteContext;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Mike Cleronb87bd162009-10-30 16:36:56 -070060import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070061import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070062import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050063import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070066 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068
Sunny Goyal5c97f512015-05-19 16:03:28 -070069 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Sunny Goyale5bb7052015-07-27 14:36:07 -070071 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070072
Sunny Goyal18b640c2015-04-17 09:24:01 -070073 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
74 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080075 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070077 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
78
Sunny Goyald3849d12015-10-29 10:28:32 -070079 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070080 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyalf076eae2016-01-11 12:25:10 -080081 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
83 @Override
84 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040085 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 return true;
87 }
88
Sunny Goyald3849d12015-10-29 10:28:32 -070089 /**
90 * Sets a provider listener.
91 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070092 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070093 synchronized (LISTENER_LOCK) {
94 mListener = listener;
95 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070096 }
97
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 @Override
99 public String getType(Uri uri) {
100 SqlArguments args = new SqlArguments(uri, null, null);
101 if (TextUtils.isEmpty(args.where)) {
102 return "vnd.android.cursor.dir/" + args.table;
103 } else {
104 return "vnd.android.cursor.item/" + args.table;
105 }
106 }
107
Sunny Goyalf076eae2016-01-11 12:25:10 -0800108 /**
109 * Overridden in tests
110 */
111 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700112 if (mOpenHelper == null) {
113 mOpenHelper = new DatabaseHelper(getContext(), this);
114 }
115 }
116
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800117 @Override
118 public Cursor query(Uri uri, String[] projection, String selection,
119 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700120 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121
122 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
123 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
124 qb.setTables(args.table);
125
Romain Guy73b979d2009-06-09 12:57:21 -0700126 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
128 result.setNotificationUri(getContext().getContentResolver(), uri);
129
130 return result;
131 }
132
Adam Cohen091440a2015-03-18 14:16:05 -0700133 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500135 if (values == null) {
136 throw new RuntimeException("Error: attempting to insert null values");
137 }
Adam Cohen71483f42014-05-15 14:04:01 -0700138 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 throw new RuntimeException("Error: attempting to add item without specifying an id");
140 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500141 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700142 return db.insert(table, nullColumnHack, values);
143 }
144
Sunny Goyald1064182015-08-13 12:08:30 -0700145 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700146 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700147 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
148 if (app != null) {
149 app.reloadWorkspace();
150 }
151 }
152 }
153
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800154 @Override
155 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700156 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800157 SqlArguments args = new SqlArguments(uri);
158
Sunny Goyald1064182015-08-13 12:08:30 -0700159 // In very limited cases, we support system|signature permission apps to modify the db.
160 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700161 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
162 return null;
163 }
164 }
165
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400167 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700168 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800169 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170
171 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700172 notifyListeners();
173
Sunny Goyalc74e4192015-09-08 14:01:03 -0700174 if (Utilities.ATLEAST_MARSHMALLOW) {
175 reloadLauncherIfExternal();
176 } else {
177 // Deprecated behavior to support legacy devices which rely on provider callbacks.
178 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
179 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
180 app.reloadWorkspace();
181 }
182
183 String notify = uri.getQueryParameter("notify");
184 if (notify == null || "true".equals(notify)) {
185 getContext().getContentResolver().notifyChange(uri, null);
186 }
187 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800188 return uri;
189 }
190
191 @Override
192 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700193 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 SqlArguments args = new SqlArguments(uri);
195
196 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
197 db.beginTransaction();
198 try {
199 int numValues = values.length;
200 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400201 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
203 return 0;
204 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800205 }
206 db.setTransactionSuccessful();
207 } finally {
208 db.endTransaction();
209 }
210
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700211 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700212 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 return values.length;
214 }
215
216 @Override
Yura085c8532014-02-11 15:15:29 +0000217 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
218 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700219 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000220 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
221 db.beginTransaction();
222 try {
223 ContentProviderResult[] result = super.applyBatch(operations);
224 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700225 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000226 return result;
227 } finally {
228 db.endTransaction();
229 }
230 }
231
232 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700234 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
236
237 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
238 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700239 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240
Sunny Goyald1064182015-08-13 12:08:30 -0700241 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return count;
243 }
244
245 @Override
246 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700247 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
249
Chris Wren1ada10d2013-09-13 18:01:38 -0400250 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800251 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
252 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700253 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800254
Sunny Goyald1064182015-08-13 12:08:30 -0700255 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800256 return count;
257 }
258
Sunny Goyal7779d622015-06-11 16:18:39 -0700259 @Override
260 public Bundle call(String method, String arg, Bundle extras) {
261 if (Binder.getCallingUid() != Process.myUid()) {
262 return null;
263 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700264 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700265
266 switch (method) {
267 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
268 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800269 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
270 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
271 Utilities.isAllowRotationPrefEnabled(getContext()));
272 } else {
273 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
274 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
275 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
276 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700277 return result;
278 }
279 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
280 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700281 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700282 synchronized (LISTENER_LOCK) {
283 if (mListener != null) {
284 mListener.onSettingsChanged(arg, value);
285 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700286 }
Sunny Goyalb171e562016-01-21 16:41:54 -0800287 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
288 LauncherBackupAgentHelper.dataChanged(getContext());
289 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700290 Bundle result = new Bundle();
291 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
292 return result;
293 }
Sunny Goyald2497482015-09-22 18:24:19 -0700294 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
295 clearFlagEmptyDbCreated();
296 return null;
297 }
298 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
299 Bundle result = new Bundle();
300 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
301 return result;
302 }
303 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
304 Bundle result = new Bundle();
305 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
306 return result;
307 }
308 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
309 Bundle result = new Bundle();
310 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
311 return result;
312 }
313 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
314 createEmptyDB();
315 return null;
316 }
317 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
318 loadDefaultFavoritesIfNecessary();
319 return null;
320 }
321 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
322 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
323 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
324 return null;
325 }
326 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
327 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
328 return null;
329 }
330 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
331 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
332 return null;
333 }
334 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800335 // Are you sure? (y/n)
336 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700337 return null;
338 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700339 }
340 return null;
341 }
342
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700343 /**
344 * Deletes any empty folder from the DB.
345 * @return Ids of deleted folders.
346 */
Sunny Goyald2497482015-09-22 18:24:19 -0700347 private ArrayList<Long> deleteEmptyFolders() {
348 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700349 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
350 db.beginTransaction();
351 try {
352 // Select folders whose id do not match any container value.
353 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
354 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
355 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
356 LauncherSettings.Favorites.CONTAINER + " FROM "
357 + TABLE_FAVORITES + ")";
358 Cursor c = db.query(TABLE_FAVORITES,
359 new String[] {LauncherSettings.Favorites._ID},
360 selection, null, null, null, null);
361 while (c.moveToNext()) {
362 folderIds.add(c.getLong(0));
363 }
364 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700365 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700366 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
367 LauncherSettings.Favorites._ID, folderIds), null);
368 }
369 db.setTransactionSuccessful();
370 } catch (SQLException ex) {
371 Log.e(TAG, ex.getMessage(), ex);
372 folderIds.clear();
373 } finally {
374 db.endTransaction();
375 }
376 return folderIds;
377 }
378
Sunny Goyalf076eae2016-01-11 12:25:10 -0800379 /**
380 * Overridden in tests
381 */
382 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400383 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400384 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700385 synchronized (LISTENER_LOCK) {
386 if (mListener != null) {
387 mListener.onLauncherProviderChange();
388 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700389 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400390 }
391
Adam Cohen091440a2015-03-18 14:16:05 -0700392 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400393 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 }
395
Brian Muramatsu5524b492012-10-02 16:55:54 -0700396 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700397 * Clears all the data for a fresh start.
398 */
Sunny Goyald2497482015-09-22 18:24:19 -0700399 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700400 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
401 }
402
Sunny Goyald2497482015-09-22 18:24:19 -0700403 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700404 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700405 }
406
Sunny Goyal42de82f2014-09-26 22:09:29 -0700407 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700408 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700409 * 1) From the app restrictions
410 * 2) From a package provided by play store
411 * 3) From a partner configuration APK, already in the system image
412 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700413 */
Sunny Goyald2497482015-09-22 18:24:19 -0700414 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700415 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700416
Winson Chungc763c4e2013-07-19 13:49:06 -0700417 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500418 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200419
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700420 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
421 if (loader == null) {
422 loader = AutoInstallsLayout.get(getContext(),
423 mOpenHelper.mAppWidgetHost, mOpenHelper);
424 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700425 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700426 final Partner partner = Partner.get(getContext().getPackageManager());
427 if (partner != null && partner.hasDefaultLayout()) {
428 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700429 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700430 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700431 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700432 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
433 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700434 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700435 }
436 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700437
Sunny Goyal9d219682014-10-23 14:21:02 -0700438 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700439 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700440 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700441 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800442
443 // There might be some partially restored DB items, due to buggy restore logic in
444 // previous versions of launcher.
445 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700446 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700447 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
448 && usingExternallyProvidedLayout) {
449 // Unable to load external layout. Cleanup and load the internal layout.
450 createEmptyDB();
451 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
452 getDefaultLayoutParser());
453 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700454 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700455 }
456 }
457
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700458 /**
459 * Creates workspace loader from an XML resource listed in the app restrictions.
460 *
461 * @return the loader if the restrictions are set and the resource exists; null otherwise.
462 */
463 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
464 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
465 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700466 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700467 return null;
468 }
469
470 Context ctx = getContext();
471 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
472 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700473 if (bundle == null) {
474 return null;
475 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700476
Sunny Goyal35ca8732015-04-06 10:45:31 -0700477 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700478 if (packageName != null) {
479 try {
480 Resources targetResources = ctx.getPackageManager()
481 .getResourcesForApplication(packageName);
482 return AutoInstallsLayout.get(ctx, packageName, targetResources,
483 mOpenHelper.mAppWidgetHost, mOpenHelper);
484 } catch (NameNotFoundException e) {
485 Log.e(TAG, "Target package for restricted profile not found", e);
486 return null;
487 }
488 }
489 return null;
490 }
491
Sunny Goyal9d219682014-10-23 14:21:02 -0700492 private DefaultLayoutParser getDefaultLayoutParser() {
493 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700494 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
496 mOpenHelper, getContext().getResources(), defaultLayout);
497 }
498
Sunny Goyald3849d12015-10-29 10:28:32 -0700499 /**
500 * Send notification that we've deleted the {@link AppWidgetHost},
501 * probably as part of the initial database creation. The receiver may
502 * want to re-call {@link AppWidgetHost#startListening()} to ensure
503 * callbacks are correctly set.
504 */
505 @Thunk void notifyAppHostReset() {
506 new MainThreadExecutor().execute(new Runnable() {
507
508 @Override
509 public void run() {
510 synchronized (LISTENER_LOCK) {
511 if (mListener != null) {
512 mListener.onAppWidgetHostReset();
513 }
514 }
515 }
516 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500517 }
518
Sunny Goyalf076eae2016-01-11 12:25:10 -0800519 /**
520 * The class is subclassed in tests to create an in-memory db.
521 */
522 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800524 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700525 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700526 private long mMaxItemId = -1;
527 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800528
Sunny Goyald3849d12015-10-29 10:28:32 -0700529 DatabaseHelper(Context context, LauncherProvider provider) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700530 this(context, provider, LauncherFiles.LAUNCHER_DB,
531 new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID));
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700532 // Table creation sometimes fails silently, which leads to a crash loop.
533 // This way, we will try to create a table every time after crash, so the device
534 // would eventually be able to recover.
535 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
536 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
537 // This operation is a no-op if the table already exists.
538 addFavoritesTable(getWritableDatabase(), true);
539 addWorkspacesTable(getWritableDatabase(), true);
540 }
541
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700542 initIds();
543 }
544
545 /**
546 * Constructor used only in tests.
547 */
548 public DatabaseHelper(
549 Context context, LauncherProvider provider, String tableName, AppWidgetHost host) {
550 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
551 mContext = context;
552 mProvider = provider;
553 mAppWidgetHost = host;
554 }
555
556 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700557 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
558 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700559 if (mMaxItemId == -1) {
560 mMaxItemId = initializeMaxItemId(getWritableDatabase());
561 }
562 if (mMaxScreenId == -1) {
563 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700564 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 }
566
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700567 private boolean tableExists(String tableName) {
568 Cursor c = getReadableDatabase().query(
569 true, "sqlite_master", new String[] {"tbl_name"},
570 "tbl_name = ?", new String[] {tableName},
571 null, null, null, null, null);
572 try {
573 return c.getCount() > 0;
574 } finally {
575 c.close();
576 }
577 }
578
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800579 @Override
580 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800581 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700582
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 mMaxItemId = 1;
584 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 addFavoritesTable(db, false);
587 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800588
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700589 // Database was just created, so wipe any previous widgets
590 if (mAppWidgetHost != null) {
591 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700592 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800593 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700594
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800595 // Fresh and clean launcher DB.
596 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800597 onEmptyDbCreated();
598 }
599
600 /**
601 * Overriden in tests.
602 */
603 protected void onEmptyDbCreated() {
604 // Set the flag for empty DB
605 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700606
607 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800608 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
609 mContext);
610 }
611
612 protected long getDefaultUserSerial() {
613 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
614 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800615 }
616
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700617 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700619 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
620 "_id INTEGER PRIMARY KEY," +
621 "title TEXT," +
622 "intent TEXT," +
623 "container INTEGER," +
624 "screen INTEGER," +
625 "cellX INTEGER," +
626 "cellY INTEGER," +
627 "spanX INTEGER," +
628 "spanY INTEGER," +
629 "itemType INTEGER," +
630 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
631 "isShortcut INTEGER," +
632 "iconType INTEGER," +
633 "iconPackage TEXT," +
634 "iconResource TEXT," +
635 "icon BLOB," +
636 "uri TEXT," +
637 "displayMode INTEGER," +
638 "appWidgetProvider TEXT," +
639 "modified INTEGER NOT NULL DEFAULT 0," +
640 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800641 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700642 "rank INTEGER NOT NULL DEFAULT 0," +
643 "options INTEGER NOT NULL DEFAULT 0" +
644 ");");
645 }
646
647 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
648 String ifNotExists = optional ? " IF NOT EXISTS " : "";
649 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800650 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400651 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
652 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 ");");
654 }
655
Adam Cohen119285e2014-04-02 16:59:08 -0700656 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700657 // Delete items directly on the workspace who's screen id doesn't exist
658 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
659 // AND container = -100"
660 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
661 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700662 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700663 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
664 " AND " +
665 LauncherSettings.Favorites.CONTAINER + " = " +
666 LauncherSettings.Favorites.CONTAINER_DESKTOP;
667 db.execSQL(removeOrphanedDesktopItems);
668
669 // Delete items contained in folders which no longer exist (after above statement)
670 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
671 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
672 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
673 " WHERE " +
674 LauncherSettings.Favorites.CONTAINER + " <> " +
675 LauncherSettings.Favorites.CONTAINER_DESKTOP +
676 " AND "
677 + LauncherSettings.Favorites.CONTAINER + " <> " +
678 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
679 " AND "
680 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
681 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
682 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
683 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
684 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700685 }
686
Winson Chungc763c4e2013-07-19 13:49:06 -0700687 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700688 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700689 }
690
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 @Override
692 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700693 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800694 switch (oldVersion) {
695 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800696 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 case 12: {
698 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
699 // to persist workspace screens and their relative order.
700 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700701 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 }
703 case 13: {
704 db.beginTransaction();
705 try {
706 // Insert new column for holding widget provider name
707 db.execSQL("ALTER TABLE favorites " +
708 "ADD COLUMN appWidgetProvider TEXT;");
709 db.setTransactionSuccessful();
710 } catch (SQLException ex) {
711 Log.e(TAG, ex.getMessage(), ex);
712 // Old version remains, which means we wipe old data
713 break;
714 } finally {
715 db.endTransaction();
716 }
717 }
718 case 14: {
719 db.beginTransaction();
720 try {
721 // Insert new column for holding update timestamp
722 db.execSQL("ALTER TABLE favorites " +
723 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
724 db.execSQL("ALTER TABLE workspaceScreens " +
725 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
726 db.setTransactionSuccessful();
727 } catch (SQLException ex) {
728 Log.e(TAG, ex.getMessage(), ex);
729 // Old version remains, which means we wipe old data
730 break;
731 } finally {
732 db.endTransaction();
733 }
734 }
735 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700736 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 // Old version remains, which means we wipe old data
738 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800739 }
740 }
741 case 16: {
742 // We use the db version upgrade here to identify users who may not have seen
743 // clings yet (because they weren't available), but for whom the clings are now
744 // available (tablet users). Because one of the possible cling flows (migration)
745 // is very destructive (wipes out workspaces), we want to prevent this from showing
746 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800747 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 }
749 case 17: {
750 // No-op
751 }
752 case 18: {
753 // Due to a data loss bug, some users may have items associated with screen ids
754 // which no longer exist. Since this can cause other problems, and since the user
755 // will never see these items anyway, we use database upgrade as an opportunity to
756 // clean things up.
757 removeOrphanedItems(db);
758 }
759 case 19: {
760 // Add userId column
761 if (!addProfileColumn(db)) {
762 // Old version remains, which means we wipe old data
763 break;
764 }
765 }
766 case 20:
767 if (!updateFolderItemsRank(db, true)) {
768 break;
769 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800770 case 21:
771 // Recreate workspace table with screen id a primary key
772 if (!recreateWorkspaceTable(db)) {
773 break;
774 }
775 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700776 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
777 // Old version remains, which means we wipe old data
778 break;
779 }
780 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700781 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700782 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700783 case 24:
784 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700785 case 25:
786 convertShortcutsToLauncherActivities(db);
787 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800788 // DB Upgraded successfully
789 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400790 }
791 }
792
Sunny Goyala2cc6242015-01-14 14:23:02 -0800793 // DB was not upgraded
794 Log.w(TAG, "Destroying all old data.");
795 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800796 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800797
Adam Cohen9b1d0622014-05-21 19:01:57 -0700798 @Override
799 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
800 // This shouldn't happen -- throw our hands up in the air and start over.
801 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
802 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700803 createEmptyDB(db);
804 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700805
Sunny Goyal42de82f2014-09-26 22:09:29 -0700806 /**
807 * Clears all the data for a fresh start.
808 */
809 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700810 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
811 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
812 onCreate(db);
813 }
814
Sunny Goyald2f38192015-02-25 10:46:34 -0800815 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
817 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
818 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700819 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700820 db.beginTransaction();
821 Cursor c = null;
822 SQLiteStatement updateStmt = null;
823
824 try {
825 // Only consider the primary user as other users can't have a shortcut.
826 long userSerial = UserManagerCompat.getInstance(mContext)
827 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
828 c = db.query(TABLE_FAVORITES, new String[] {
829 Favorites._ID,
830 Favorites.INTENT,
831 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
832 null, null, null, null);
833
834 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
835 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
836
837 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
838 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
839
840 while (c.moveToNext()) {
841 String intentDescription = c.getString(intentIndex);
842 Intent intent;
843 try {
844 intent = Intent.parseUri(intentDescription, 0);
845 } catch (URISyntaxException e) {
846 Log.e(TAG, "Unable to parse intent", e);
847 continue;
848 }
849
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700850 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700851 continue;
852 }
853
854 long id = c.getLong(idIndex);
855 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700856 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700857 }
858 db.setTransactionSuccessful();
859 } catch (SQLException ex) {
860 Log.w(TAG, "Error deduping shortcuts", ex);
861 } finally {
862 db.endTransaction();
863 if (c != null) {
864 c.close();
865 }
866 if (updateStmt != null) {
867 updateStmt.close();
868 }
869 }
870 }
871
872 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800873 * Recreates workspace table and migrates data to the new table.
874 */
875 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
876 db.beginTransaction();
877 try {
878 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
879 new String[] {LauncherSettings.WorkspaceScreens._ID},
880 null, null, null, null,
881 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
882 ArrayList<Long> sortedIDs = new ArrayList<Long>();
883 long maxId = 0;
884 try {
885 while (c.moveToNext()) {
886 Long id = c.getLong(0);
887 if (!sortedIDs.contains(id)) {
888 sortedIDs.add(id);
889 maxId = Math.max(maxId, id);
890 }
891 }
892 } finally {
893 c.close();
894 }
895
896 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700897 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800898
899 // Add all screen ids back
900 int total = sortedIDs.size();
901 for (int i = 0; i < total; i++) {
902 ContentValues values = new ContentValues();
903 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
904 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
905 addModifiedTime(values);
906 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
907 }
908 db.setTransactionSuccessful();
909 mMaxScreenId = maxId;
910 } catch (SQLException ex) {
911 // Old version remains, which means we wipe old data
912 Log.e(TAG, ex.getMessage(), ex);
913 return false;
914 } finally {
915 db.endTransaction();
916 }
917 return true;
918 }
919
Adam Cohen091440a2015-03-18 14:16:05 -0700920 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800921 db.beginTransaction();
922 try {
923 if (addRankColumn) {
924 // Insert new column for holding rank
925 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
926 }
927
928 // Get a map for folder ID to folder width
929 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
930 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
931 + " GROUP BY container;",
932 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
933
934 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800935 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
936 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800937 new Object[] {c.getLong(1) + 1, c.getLong(0)});
938 }
939
940 c.close();
941 db.setTransactionSuccessful();
942 } catch (SQLException ex) {
943 // Old version remains, which means we wipe old data
944 Log.e(TAG, ex.getMessage(), ex);
945 return false;
946 } finally {
947 db.endTransaction();
948 }
949 return true;
950 }
951
Kenny Guyed131872014-04-30 03:02:21 +0100952 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700953 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
954 // Default to the serial number of this user, for older
955 // shortcuts.
956 long userSerialNumber = userManager.getSerialNumberForUser(
957 UserHandleCompat.myUserHandle());
958 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
959 }
960
961 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100962 db.beginTransaction();
963 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700964 db.execSQL("ALTER TABLE favorites ADD COLUMN "
965 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100966 db.setTransactionSuccessful();
967 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100968 Log.e(TAG, ex.getMessage(), ex);
969 return false;
970 } finally {
971 db.endTransaction();
972 }
973 return true;
974 }
975
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700976 // Generates a new ID to use for an object in your database. This method should be only
977 // called from the main UI thread. As an exception, we do call it when we call the
978 // constructor from the worker thread; however, this doesn't extend until after the
979 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
980 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700981 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700982 public long generateNewItemId() {
983 if (mMaxItemId < 0) {
984 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700985 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700986 mMaxItemId += 1;
987 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700988 }
989
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700990 @Override
991 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
992 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
993 }
994
Chris Wren5dee7af2013-12-20 17:22:11 -0500995 public void checkId(String table, ContentValues values) {
996 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
997 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
998 mMaxScreenId = Math.max(id, mMaxScreenId);
999 } else {
1000 mMaxItemId = Math.max(id, mMaxItemId);
1001 }
1002 }
1003
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001005 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -07001006 }
1007
1008 // Generates a new ID to use for an workspace screen in your database. This method
1009 // should be only called from the main UI thread. As an exception, we do call it when we
1010 // call the constructor from the worker thread; however, this doesn't extend until after the
1011 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1012 // after that point
1013 public long generateNewScreenId() {
1014 if (mMaxScreenId < 0) {
1015 throw new RuntimeException("Error: max screen id was not initialized");
1016 }
1017 mMaxScreenId += 1;
1018 return mMaxScreenId;
1019 }
1020
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001022 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001023 }
1024
Adam Cohen091440a2015-03-18 14:16:05 -07001025 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001026 // 1. Ensure that externally added items have a valid item id
1027 long id = generateNewItemId();
1028 values.put(LauncherSettings.Favorites._ID, id);
1029
1030 // 2. In the case of an app widget, and if no app widget id is specified, we
1031 // attempt allocate and bind the widget.
1032 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1033 if (itemType != null &&
1034 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1035 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1036
1037 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1038 ComponentName cn = ComponentName.unflattenFromString(
1039 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1040
1041 if (cn != null) {
1042 try {
1043 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001044 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001045 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001046 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001047 }
1048 } catch (RuntimeException e) {
1049 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001050 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001051 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001052 } else {
1053 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001054 }
1055 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001056
1057 // Add screen id if not present
1058 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1059 if (!addScreenIdIfNecessary(screenId)) {
1060 return false;
1061 }
Adam Cohena043fa82014-07-23 14:49:38 -07001062 return true;
1063 }
1064
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001065 // Returns true of screen id exists, or if successfully added
1066 private boolean addScreenIdIfNecessary(long screenId) {
1067 if (!hasScreenId(screenId)) {
1068 int rank = getMaxScreenRank() + 1;
1069
1070 ContentValues v = new ContentValues();
1071 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1072 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1073 if (dbInsertAndCheck(this, getWritableDatabase(),
1074 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1075 return false;
1076 }
1077 }
1078 return true;
1079 }
1080
1081 private boolean hasScreenId(long screenId) {
1082 SQLiteDatabase db = getWritableDatabase();
1083 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1084 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1085 if (c != null) {
1086 int count = c.getCount();
1087 c.close();
1088 return count > 0;
1089 } else {
1090 return false;
1091 }
1092 }
1093
1094 private int getMaxScreenRank() {
1095 SQLiteDatabase db = getWritableDatabase();
1096 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1097 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1098
1099 // get the result
1100 final int maxRankIndex = 0;
1101 int rank = -1;
1102 if (c != null && c.moveToNext()) {
1103 rank = c.getInt(maxRankIndex);
1104 }
1105 if (c != null) {
1106 c.close();
1107 }
1108
1109 return rank;
1110 }
1111
Adam Cohen091440a2015-03-18 14:16:05 -07001112 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001113 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001114 // TODO: Use multiple loaders with fall-back and transaction.
1115 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001116
1117 // Add the screens specified by the items above
1118 Collections.sort(screenIds);
1119 int rank = 0;
1120 ContentValues values = new ContentValues();
1121 for (Long id : screenIds) {
1122 values.clear();
1123 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1124 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1125 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1126 throw new RuntimeException("Failed initialize screen table"
1127 + "from default layout");
1128 }
1129 rank++;
1130 }
1131
1132 // Ensure that the max ids are initialized
1133 mMaxItemId = initializeMaxItemId(db);
1134 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001135
Adam Cohen71483f42014-05-15 14:04:01 -07001136 return count;
1137 }
1138
Adam Cohen091440a2015-03-18 14:16:05 -07001139 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001140 final ContentResolver resolver = mContext.getContentResolver();
1141 Cursor c = null;
1142 int count = 0;
1143 int curScreen = 0;
1144
1145 try {
1146 c = resolver.query(uri, null, null, null, "title ASC");
1147 } catch (Exception e) {
1148 // Ignore
1149 }
1150
Dan Sandlerd5024042014-01-09 15:01:33 -05001151 // We already have a favorites database in the old provider
1152 if (c != null) {
1153 try {
1154 if (c.getCount() > 0) {
1155 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1156 final int intentIndex
1157 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1158 final int titleIndex
1159 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1160 final int iconTypeIndex
1161 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1162 final int iconIndex
1163 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1164 final int iconPackageIndex
1165 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1166 final int iconResourceIndex
1167 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1168 final int containerIndex
1169 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1170 final int itemTypeIndex
1171 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1172 final int screenIndex
1173 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1174 final int cellXIndex
1175 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1176 final int cellYIndex
1177 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001178 final int profileIndex
1179 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001180
1181 int i = 0;
1182 int curX = 0;
1183 int curY = 0;
1184
1185 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001186 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1187 final int width = (int) profile.numColumns;
1188 final int height = (int) profile.numRows;
1189 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001190
1191 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1192
Adam Cohen72960972014-01-15 18:13:55 -08001193 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1194 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001195 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001196
1197 while (c.moveToNext()) {
1198 final int itemType = c.getInt(itemTypeIndex);
1199 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1200 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1201 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1202 continue;
1203 }
1204
1205 final int cellX = c.getInt(cellXIndex);
1206 final int cellY = c.getInt(cellYIndex);
1207 final int screen = c.getInt(screenIndex);
1208 int container = c.getInt(containerIndex);
1209 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001210
1211 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1212 UserHandleCompat userHandle;
1213 final long userSerialNumber;
1214 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1215 userSerialNumber = c.getInt(profileIndex);
1216 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1217 } else {
1218 // Default to the serial number of this user, for older
1219 // shortcuts.
1220 userHandle = UserHandleCompat.myUserHandle();
1221 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1222 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001223
1224 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001225 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001226 continue;
1227 }
1228
Dan Sandlerd5024042014-01-09 15:01:33 -05001229 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001230
1231 final Intent intent;
1232 final ComponentName cn;
1233 try {
1234 intent = Intent.parseUri(intentStr, 0);
1235 } catch (URISyntaxException e) {
1236 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001237 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001238 continue;
1239 }
1240
1241 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001242 if (TextUtils.isEmpty(intentStr)) {
1243 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001244 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001245 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001246 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001247 !LauncherModel.isValidPackageActivity(mContext, cn,
1248 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001249 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001250 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001251 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001252 } else if (container ==
1253 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1254 // Dedupe icons directly on the workspace
1255
Adam Cohen556f6132014-01-15 15:18:08 -08001256 // Canonicalize
1257 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001258 // does not, so we clear that out to keep them the same.
1259 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001260 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001261 int flags = intent.getFlags();
1262 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001263 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001264 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001265 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001266 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001267 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001268 } else {
1269 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001270 }
1271 }
1272 }
1273
1274 ContentValues values = new ContentValues(c.getColumnCount());
1275 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1276 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1277 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1278 values.put(LauncherSettings.Favorites.ICON_TYPE,
1279 c.getInt(iconTypeIndex));
1280 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1281 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1282 c.getString(iconPackageIndex));
1283 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1284 c.getString(iconResourceIndex));
1285 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1286 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001287 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001288
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001289 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1290 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001291 }
1292
1293 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1294 // In a folder or in the hotseat, preserve position
1295 values.put(LauncherSettings.Favorites.SCREEN, screen);
1296 values.put(LauncherSettings.Favorites.CELLX, cellX);
1297 values.put(LauncherSettings.Favorites.CELLY, cellY);
1298 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001299 // For items contained directly on one of the workspace screen,
1300 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001301 }
1302
1303 values.put(LauncherSettings.Favorites.CONTAINER, container);
1304
Adam Cohen72960972014-01-15 18:13:55 -08001305 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1306 shortcuts.add(values);
1307 } else {
1308 folders.add(values);
1309 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001310 }
1311
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001312 // Now that we have all the hotseat icons, let's go through them left-right
1313 // and assign valid locations for them in the new hotseat
1314 final int N = hotseat.size();
1315 for (int idx=0; idx<N; idx++) {
1316 int hotseatX = hotseat.keyAt(idx);
1317 ContentValues values = hotseat.valueAt(idx);
1318
Adam Cohen2e6da152015-05-06 11:42:25 -07001319 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001320 // let's drop this in the next available hole in the hotseat
1321 while (++hotseatX < hotseatWidth) {
1322 if (hotseat.get(hotseatX) == null) {
1323 // found a spot! move it here
1324 values.put(LauncherSettings.Favorites.SCREEN,
1325 hotseatX);
1326 break;
1327 }
1328 }
1329 }
1330 if (hotseatX >= hotseatWidth) {
1331 // no room for you in the hotseat? it's off to the desktop with you
1332 values.put(LauncherSettings.Favorites.CONTAINER,
1333 Favorites.CONTAINER_DESKTOP);
1334 }
1335 }
1336
Adam Cohen72960972014-01-15 18:13:55 -08001337 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1338 // Folders first
1339 allItems.addAll(folders);
1340 // Then shortcuts
1341 allItems.addAll(shortcuts);
1342
1343 // Layout all the folders
1344 for (ContentValues values: allItems) {
1345 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1346 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1347 // Hotseat items and folder items have already had their
1348 // location information set. Nothing to be done here.
1349 continue;
1350 }
1351 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1352 values.put(LauncherSettings.Favorites.CELLX, curX);
1353 values.put(LauncherSettings.Favorites.CELLY, curY);
1354 curX = (curX + 1) % width;
1355 if (curX == 0) {
1356 curY = (curY + 1);
1357 }
1358 // Leave the last row of icons blank on every screen
1359 if (curY == height - 1) {
1360 curScreen = (int) generateNewScreenId();
1361 curY = 0;
1362 }
1363 }
1364
1365 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001366 db.beginTransaction();
1367 try {
Adam Cohen72960972014-01-15 18:13:55 -08001368 for (ContentValues row: allItems) {
1369 if (row == null) continue;
1370 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001371 < 0) {
1372 return;
1373 } else {
1374 count++;
1375 }
1376 }
1377 db.setTransactionSuccessful();
1378 } finally {
1379 db.endTransaction();
1380 }
1381 }
1382
1383 db.beginTransaction();
1384 try {
1385 for (i=0; i<=curScreen; i++) {
1386 final ContentValues values = new ContentValues();
1387 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1388 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1389 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1390 < 0) {
1391 return;
1392 }
1393 }
1394 db.setTransactionSuccessful();
1395 } finally {
1396 db.endTransaction();
1397 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001398
1399 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001400 }
1401 } finally {
1402 c.close();
1403 }
1404 }
1405
Sunny Goyala1365452015-10-01 15:46:24 -07001406 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1407 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001408
1409 // ensure that new screens are created to hold these icons
1410 setFlagJustLoadedOldDb();
1411
1412 // Update max IDs; very important since we just grabbed IDs from another database
1413 mMaxItemId = initializeMaxItemId(db);
1414 mMaxScreenId = initializeMaxScreenId(db);
1415 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1416 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001417 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001418
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001419 /**
1420 * @return the max _id in the provided table.
1421 */
Adam Cohen091440a2015-03-18 14:16:05 -07001422 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001423 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1424 // get the result
1425 long id = -1;
1426 if (c != null && c.moveToNext()) {
1427 id = c.getLong(0);
1428 }
1429 if (c != null) {
1430 c.close();
1431 }
1432
1433 if (id == -1) {
1434 throw new RuntimeException("Error: could not query max id in " + table);
1435 }
1436
1437 return id;
1438 }
1439
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001440 static class SqlArguments {
1441 public final String table;
1442 public final String where;
1443 public final String[] args;
1444
1445 SqlArguments(Uri url, String where, String[] args) {
1446 if (url.getPathSegments().size() == 1) {
1447 this.table = url.getPathSegments().get(0);
1448 this.where = where;
1449 this.args = args;
1450 } else if (url.getPathSegments().size() != 2) {
1451 throw new IllegalArgumentException("Invalid URI: " + url);
1452 } else if (!TextUtils.isEmpty(where)) {
1453 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1454 } else {
1455 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001456 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001457 this.args = null;
1458 }
1459 }
1460
1461 SqlArguments(Uri url) {
1462 if (url.getPathSegments().size() == 1) {
1463 table = url.getPathSegments().get(0);
1464 where = null;
1465 args = null;
1466 } else {
1467 throw new IllegalArgumentException("Invalid URI: " + url);
1468 }
1469 }
1470 }
Adam Cohen72960972014-01-15 18:13:55 -08001471}