blob: a57f680378946ac94ecf4dde73277c3af12b052a [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;
Adam Cohen091440a2015-03-18 14:16:05 -070057import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070058
Mike Cleronb87bd162009-10-30 16:36:56 -070059import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070060import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070061import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050062import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070065 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080066 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067
Sunny Goyal5c97f512015-05-19 16:03:28 -070068 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyale5bb7052015-07-27 14:36:07 -070070 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070071
Sunny Goyal18b640c2015-04-17 09:24:01 -070072 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
73 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080074 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070076 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
77
Sunny Goyald3849d12015-10-29 10:28:32 -070078 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070079 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyalf076eae2016-01-11 12:25:10 -080080 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
82 @Override
83 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040084 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 return true;
86 }
87
Sunny Goyald3849d12015-10-29 10:28:32 -070088 /**
89 * Sets a provider listener.
90 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070091 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070092 synchronized (LISTENER_LOCK) {
93 mListener = listener;
94 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070095 }
96
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097 @Override
98 public String getType(Uri uri) {
99 SqlArguments args = new SqlArguments(uri, null, null);
100 if (TextUtils.isEmpty(args.where)) {
101 return "vnd.android.cursor.dir/" + args.table;
102 } else {
103 return "vnd.android.cursor.item/" + args.table;
104 }
105 }
106
Sunny Goyalf076eae2016-01-11 12:25:10 -0800107 /**
108 * Overridden in tests
109 */
110 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700111 if (mOpenHelper == null) {
112 mOpenHelper = new DatabaseHelper(getContext(), this);
113 }
114 }
115
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116 @Override
117 public Cursor query(Uri uri, String[] projection, String selection,
118 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700119 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120
121 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
122 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
123 qb.setTables(args.table);
124
Romain Guy73b979d2009-06-09 12:57:21 -0700125 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
127 result.setNotificationUri(getContext().getContentResolver(), uri);
128
129 return result;
130 }
131
Adam Cohen091440a2015-03-18 14:16:05 -0700132 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500134 if (values == null) {
135 throw new RuntimeException("Error: attempting to insert null values");
136 }
Adam Cohen71483f42014-05-15 14:04:01 -0700137 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 throw new RuntimeException("Error: attempting to add item without specifying an id");
139 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500140 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 return db.insert(table, nullColumnHack, values);
142 }
143
Sunny Goyald1064182015-08-13 12:08:30 -0700144 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700145 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700146 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
147 if (app != null) {
148 app.reloadWorkspace();
149 }
150 }
151 }
152
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 @Override
154 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700155 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156 SqlArguments args = new SqlArguments(uri);
157
Sunny Goyald1064182015-08-13 12:08:30 -0700158 // In very limited cases, we support system|signature permission apps to modify the db.
159 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700160 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
161 return null;
162 }
163 }
164
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400166 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700167 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800168 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800169
170 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700171 notifyListeners();
172
Sunny Goyalc74e4192015-09-08 14:01:03 -0700173 if (Utilities.ATLEAST_MARSHMALLOW) {
174 reloadLauncherIfExternal();
175 } else {
176 // Deprecated behavior to support legacy devices which rely on provider callbacks.
177 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
178 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
179 app.reloadWorkspace();
180 }
181
182 String notify = uri.getQueryParameter("notify");
183 if (notify == null || "true".equals(notify)) {
184 getContext().getContentResolver().notifyChange(uri, null);
185 }
186 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187 return uri;
188 }
189
190 @Override
191 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700192 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193 SqlArguments args = new SqlArguments(uri);
194
195 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
196 db.beginTransaction();
197 try {
198 int numValues = values.length;
199 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400200 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700201 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
202 return 0;
203 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204 }
205 db.setTransactionSuccessful();
206 } finally {
207 db.endTransaction();
208 }
209
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700210 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700211 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 return values.length;
213 }
214
215 @Override
Yura085c8532014-02-11 15:15:29 +0000216 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
217 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700218 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000219 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
220 db.beginTransaction();
221 try {
222 ContentProviderResult[] result = super.applyBatch(operations);
223 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700224 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000225 return result;
226 } finally {
227 db.endTransaction();
228 }
229 }
230
231 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700233 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
235
236 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
237 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700238 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239
Sunny Goyald1064182015-08-13 12:08:30 -0700240 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 return count;
242 }
243
244 @Override
245 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700246 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800247 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
248
Chris Wren1ada10d2013-09-13 18:01:38 -0400249 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
251 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700252 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253
Sunny Goyald1064182015-08-13 12:08:30 -0700254 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800255 return count;
256 }
257
Sunny Goyal7779d622015-06-11 16:18:39 -0700258 @Override
259 public Bundle call(String method, String arg, Bundle extras) {
260 if (Binder.getCallingUid() != Process.myUid()) {
261 return null;
262 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700263 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700264
265 switch (method) {
266 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
267 Bundle result = new Bundle();
268 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700269 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
270 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700271 return result;
272 }
273 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
274 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700275 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700276 synchronized (LISTENER_LOCK) {
277 if (mListener != null) {
278 mListener.onSettingsChanged(arg, value);
279 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700280 }
Sunny Goyalb171e562016-01-21 16:41:54 -0800281 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
282 LauncherBackupAgentHelper.dataChanged(getContext());
283 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700284 Bundle result = new Bundle();
285 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
286 return result;
287 }
Sunny Goyald2497482015-09-22 18:24:19 -0700288 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
289 clearFlagEmptyDbCreated();
290 return null;
291 }
292 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
293 Bundle result = new Bundle();
294 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
295 return result;
296 }
297 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
298 Bundle result = new Bundle();
299 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
300 return result;
301 }
302 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
303 Bundle result = new Bundle();
304 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
305 return result;
306 }
307 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
308 createEmptyDB();
309 return null;
310 }
311 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
312 loadDefaultFavoritesIfNecessary();
313 return null;
314 }
315 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
316 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
317 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
318 return null;
319 }
320 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
321 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
322 return null;
323 }
324 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
325 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
326 return null;
327 }
328 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800329 // Are you sure? (y/n)
330 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700331 return null;
332 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700333 }
334 return null;
335 }
336
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700337 /**
338 * Deletes any empty folder from the DB.
339 * @return Ids of deleted folders.
340 */
Sunny Goyald2497482015-09-22 18:24:19 -0700341 private ArrayList<Long> deleteEmptyFolders() {
342 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700343 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
344 db.beginTransaction();
345 try {
346 // Select folders whose id do not match any container value.
347 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
348 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
349 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
350 LauncherSettings.Favorites.CONTAINER + " FROM "
351 + TABLE_FAVORITES + ")";
352 Cursor c = db.query(TABLE_FAVORITES,
353 new String[] {LauncherSettings.Favorites._ID},
354 selection, null, null, null, null);
355 while (c.moveToNext()) {
356 folderIds.add(c.getLong(0));
357 }
358 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700359 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700360 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
361 LauncherSettings.Favorites._ID, folderIds), null);
362 }
363 db.setTransactionSuccessful();
364 } catch (SQLException ex) {
365 Log.e(TAG, ex.getMessage(), ex);
366 folderIds.clear();
367 } finally {
368 db.endTransaction();
369 }
370 return folderIds;
371 }
372
Sunny Goyalf076eae2016-01-11 12:25:10 -0800373 /**
374 * Overridden in tests
375 */
376 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400377 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400378 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700379 synchronized (LISTENER_LOCK) {
380 if (mListener != null) {
381 mListener.onLauncherProviderChange();
382 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700383 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400384 }
385
Adam Cohen091440a2015-03-18 14:16:05 -0700386 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400387 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800388 }
389
Brian Muramatsu5524b492012-10-02 16:55:54 -0700390 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700391 * Clears all the data for a fresh start.
392 */
Sunny Goyald2497482015-09-22 18:24:19 -0700393 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700394 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
395 }
396
Sunny Goyald2497482015-09-22 18:24:19 -0700397 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700398 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700399 }
400
Sunny Goyal42de82f2014-09-26 22:09:29 -0700401 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700402 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700403 * 1) From the app restrictions
404 * 2) From a package provided by play store
405 * 3) From a partner configuration APK, already in the system image
406 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700407 */
Sunny Goyald2497482015-09-22 18:24:19 -0700408 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700409 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700410
Winson Chungc763c4e2013-07-19 13:49:06 -0700411 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500412 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200413
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700414 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
415 if (loader == null) {
416 loader = AutoInstallsLayout.get(getContext(),
417 mOpenHelper.mAppWidgetHost, mOpenHelper);
418 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700419 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700420 final Partner partner = Partner.get(getContext().getPackageManager());
421 if (partner != null && partner.hasDefaultLayout()) {
422 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700423 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700424 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700425 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700426 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
427 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700428 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700429 }
430 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700431
Sunny Goyal9d219682014-10-23 14:21:02 -0700432 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700433 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700434 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700435 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800436
437 // There might be some partially restored DB items, due to buggy restore logic in
438 // previous versions of launcher.
439 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700440 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700441 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
442 && usingExternallyProvidedLayout) {
443 // Unable to load external layout. Cleanup and load the internal layout.
444 createEmptyDB();
445 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
446 getDefaultLayoutParser());
447 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700448 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700449 }
450 }
451
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700452 /**
453 * Creates workspace loader from an XML resource listed in the app restrictions.
454 *
455 * @return the loader if the restrictions are set and the resource exists; null otherwise.
456 */
457 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
458 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
459 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700460 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700461 return null;
462 }
463
464 Context ctx = getContext();
465 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
466 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700467 if (bundle == null) {
468 return null;
469 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700470
Sunny Goyal35ca8732015-04-06 10:45:31 -0700471 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700472 if (packageName != null) {
473 try {
474 Resources targetResources = ctx.getPackageManager()
475 .getResourcesForApplication(packageName);
476 return AutoInstallsLayout.get(ctx, packageName, targetResources,
477 mOpenHelper.mAppWidgetHost, mOpenHelper);
478 } catch (NameNotFoundException e) {
479 Log.e(TAG, "Target package for restricted profile not found", e);
480 return null;
481 }
482 }
483 return null;
484 }
485
Sunny Goyal9d219682014-10-23 14:21:02 -0700486 private DefaultLayoutParser getDefaultLayoutParser() {
487 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700488 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700489 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
490 mOpenHelper, getContext().getResources(), defaultLayout);
491 }
492
Sunny Goyald3849d12015-10-29 10:28:32 -0700493 /**
494 * Send notification that we've deleted the {@link AppWidgetHost},
495 * probably as part of the initial database creation. The receiver may
496 * want to re-call {@link AppWidgetHost#startListening()} to ensure
497 * callbacks are correctly set.
498 */
499 @Thunk void notifyAppHostReset() {
500 new MainThreadExecutor().execute(new Runnable() {
501
502 @Override
503 public void run() {
504 synchronized (LISTENER_LOCK) {
505 if (mListener != null) {
506 mListener.onAppWidgetHostReset();
507 }
508 }
509 }
510 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500511 }
512
Sunny Goyalf076eae2016-01-11 12:25:10 -0800513 /**
514 * The class is subclassed in tests to create an in-memory db.
515 */
516 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700517 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700519 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700520 private long mMaxItemId = -1;
521 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800522
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 DatabaseHelper(Context context, LauncherProvider provider) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100524 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800525 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700526 mProvider = provider;
527
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700528 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700529
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700530 // Table creation sometimes fails silently, which leads to a crash loop.
531 // This way, we will try to create a table every time after crash, so the device
532 // would eventually be able to recover.
533 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
534 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
535 // This operation is a no-op if the table already exists.
536 addFavoritesTable(getWritableDatabase(), true);
537 addWorkspacesTable(getWritableDatabase(), true);
538 }
539
Winson Chung3d503fb2011-07-13 17:25:49 -0700540 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
541 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700542 if (mMaxItemId == -1) {
543 mMaxItemId = initializeMaxItemId(getWritableDatabase());
544 }
545 if (mMaxScreenId == -1) {
546 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700547 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 }
549
Sunny Goyalf076eae2016-01-11 12:25:10 -0800550 /**
551 * Constructor used only in tests.
552 */
553 public DatabaseHelper(Context context, LauncherProvider provider, String tableName) {
554 super(context, tableName, null, DATABASE_VERSION);
555 mContext = context;
556 mProvider = provider;
557
558 mAppWidgetHost = null;
559 mMaxItemId = initializeMaxItemId(getWritableDatabase());
560 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
561 }
562
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700563 private boolean tableExists(String tableName) {
564 Cursor c = getReadableDatabase().query(
565 true, "sqlite_master", new String[] {"tbl_name"},
566 "tbl_name = ?", new String[] {tableName},
567 null, null, null, null, null);
568 try {
569 return c.getCount() > 0;
570 } finally {
571 c.close();
572 }
573 }
574
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 @Override
576 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800577 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700578
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 mMaxItemId = 1;
580 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700581
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700582 addFavoritesTable(db, false);
583 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700585 // Database was just created, so wipe any previous widgets
586 if (mAppWidgetHost != null) {
587 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700588 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700590
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800591 // Fresh and clean launcher DB.
592 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800593 onEmptyDbCreated();
594 }
595
596 /**
597 * Overriden in tests.
598 */
599 protected void onEmptyDbCreated() {
600 // Set the flag for empty DB
601 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700602
603 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800604 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
605 mContext);
606 }
607
608 protected long getDefaultUserSerial() {
609 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
610 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
612
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700613 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700614 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700615 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
616 "_id INTEGER PRIMARY KEY," +
617 "title TEXT," +
618 "intent TEXT," +
619 "container INTEGER," +
620 "screen INTEGER," +
621 "cellX INTEGER," +
622 "cellY INTEGER," +
623 "spanX INTEGER," +
624 "spanY INTEGER," +
625 "itemType INTEGER," +
626 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
627 "isShortcut INTEGER," +
628 "iconType INTEGER," +
629 "iconPackage TEXT," +
630 "iconResource TEXT," +
631 "icon BLOB," +
632 "uri TEXT," +
633 "displayMode INTEGER," +
634 "appWidgetProvider TEXT," +
635 "modified INTEGER NOT NULL DEFAULT 0," +
636 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800637 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700638 "rank INTEGER NOT NULL DEFAULT 0," +
639 "options INTEGER NOT NULL DEFAULT 0" +
640 ");");
641 }
642
643 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
644 String ifNotExists = optional ? " IF NOT EXISTS " : "";
645 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800646 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400647 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
648 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700649 ");");
650 }
651
Adam Cohen119285e2014-04-02 16:59:08 -0700652 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700653 // Delete items directly on the workspace who's screen id doesn't exist
654 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
655 // AND container = -100"
656 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
657 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700658 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700659 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
660 " AND " +
661 LauncherSettings.Favorites.CONTAINER + " = " +
662 LauncherSettings.Favorites.CONTAINER_DESKTOP;
663 db.execSQL(removeOrphanedDesktopItems);
664
665 // Delete items contained in folders which no longer exist (after above statement)
666 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
667 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
668 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
669 " WHERE " +
670 LauncherSettings.Favorites.CONTAINER + " <> " +
671 LauncherSettings.Favorites.CONTAINER_DESKTOP +
672 " AND "
673 + LauncherSettings.Favorites.CONTAINER + " <> " +
674 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
675 " AND "
676 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
677 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
678 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
679 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
680 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700681 }
682
Winson Chungc763c4e2013-07-19 13:49:06 -0700683 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700684 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700685 }
686
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 @Override
688 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700689 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800690 switch (oldVersion) {
691 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800692 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800693 case 12: {
694 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
695 // to persist workspace screens and their relative order.
696 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700697 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800698 }
699 case 13: {
700 db.beginTransaction();
701 try {
702 // Insert new column for holding widget provider name
703 db.execSQL("ALTER TABLE favorites " +
704 "ADD COLUMN appWidgetProvider TEXT;");
705 db.setTransactionSuccessful();
706 } catch (SQLException ex) {
707 Log.e(TAG, ex.getMessage(), ex);
708 // Old version remains, which means we wipe old data
709 break;
710 } finally {
711 db.endTransaction();
712 }
713 }
714 case 14: {
715 db.beginTransaction();
716 try {
717 // Insert new column for holding update timestamp
718 db.execSQL("ALTER TABLE favorites " +
719 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
720 db.execSQL("ALTER TABLE workspaceScreens " +
721 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
722 db.setTransactionSuccessful();
723 } catch (SQLException ex) {
724 Log.e(TAG, ex.getMessage(), ex);
725 // Old version remains, which means we wipe old data
726 break;
727 } finally {
728 db.endTransaction();
729 }
730 }
731 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700732 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 // Old version remains, which means we wipe old data
734 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 }
736 }
737 case 16: {
738 // We use the db version upgrade here to identify users who may not have seen
739 // clings yet (because they weren't available), but for whom the clings are now
740 // available (tablet users). Because one of the possible cling flows (migration)
741 // is very destructive (wipes out workspaces), we want to prevent this from showing
742 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800743 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800744 }
745 case 17: {
746 // No-op
747 }
748 case 18: {
749 // Due to a data loss bug, some users may have items associated with screen ids
750 // which no longer exist. Since this can cause other problems, and since the user
751 // will never see these items anyway, we use database upgrade as an opportunity to
752 // clean things up.
753 removeOrphanedItems(db);
754 }
755 case 19: {
756 // Add userId column
757 if (!addProfileColumn(db)) {
758 // Old version remains, which means we wipe old data
759 break;
760 }
761 }
762 case 20:
763 if (!updateFolderItemsRank(db, true)) {
764 break;
765 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800766 case 21:
767 // Recreate workspace table with screen id a primary key
768 if (!recreateWorkspaceTable(db)) {
769 break;
770 }
771 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700772 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
773 // Old version remains, which means we wipe old data
774 break;
775 }
776 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700777 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700778 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700779 case 24:
780 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700781 case 25:
782 convertShortcutsToLauncherActivities(db);
783 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800784 // DB Upgraded successfully
785 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400786 }
787 }
788
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 // DB was not upgraded
790 Log.w(TAG, "Destroying all old data.");
791 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800792 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800793
Adam Cohen9b1d0622014-05-21 19:01:57 -0700794 @Override
795 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
796 // This shouldn't happen -- throw our hands up in the air and start over.
797 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
798 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700799 createEmptyDB(db);
800 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700801
Sunny Goyal42de82f2014-09-26 22:09:29 -0700802 /**
803 * Clears all the data for a fresh start.
804 */
805 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700806 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
807 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
808 onCreate(db);
809 }
810
Sunny Goyald2f38192015-02-25 10:46:34 -0800811 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700812 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
813 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
814 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700815 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 db.beginTransaction();
817 Cursor c = null;
818 SQLiteStatement updateStmt = null;
819
820 try {
821 // Only consider the primary user as other users can't have a shortcut.
822 long userSerial = UserManagerCompat.getInstance(mContext)
823 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
824 c = db.query(TABLE_FAVORITES, new String[] {
825 Favorites._ID,
826 Favorites.INTENT,
827 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
828 null, null, null, null);
829
830 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
831 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
832
833 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
834 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
835
836 while (c.moveToNext()) {
837 String intentDescription = c.getString(intentIndex);
838 Intent intent;
839 try {
840 intent = Intent.parseUri(intentDescription, 0);
841 } catch (URISyntaxException e) {
842 Log.e(TAG, "Unable to parse intent", e);
843 continue;
844 }
845
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700846 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700847 continue;
848 }
849
850 long id = c.getLong(idIndex);
851 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700852 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700853 }
854 db.setTransactionSuccessful();
855 } catch (SQLException ex) {
856 Log.w(TAG, "Error deduping shortcuts", ex);
857 } finally {
858 db.endTransaction();
859 if (c != null) {
860 c.close();
861 }
862 if (updateStmt != null) {
863 updateStmt.close();
864 }
865 }
866 }
867
868 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800869 * Recreates workspace table and migrates data to the new table.
870 */
871 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
872 db.beginTransaction();
873 try {
874 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
875 new String[] {LauncherSettings.WorkspaceScreens._ID},
876 null, null, null, null,
877 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
878 ArrayList<Long> sortedIDs = new ArrayList<Long>();
879 long maxId = 0;
880 try {
881 while (c.moveToNext()) {
882 Long id = c.getLong(0);
883 if (!sortedIDs.contains(id)) {
884 sortedIDs.add(id);
885 maxId = Math.max(maxId, id);
886 }
887 }
888 } finally {
889 c.close();
890 }
891
892 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700893 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800894
895 // Add all screen ids back
896 int total = sortedIDs.size();
897 for (int i = 0; i < total; i++) {
898 ContentValues values = new ContentValues();
899 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
900 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
901 addModifiedTime(values);
902 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
903 }
904 db.setTransactionSuccessful();
905 mMaxScreenId = maxId;
906 } catch (SQLException ex) {
907 // Old version remains, which means we wipe old data
908 Log.e(TAG, ex.getMessage(), ex);
909 return false;
910 } finally {
911 db.endTransaction();
912 }
913 return true;
914 }
915
Adam Cohen091440a2015-03-18 14:16:05 -0700916 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800917 db.beginTransaction();
918 try {
919 if (addRankColumn) {
920 // Insert new column for holding rank
921 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
922 }
923
924 // Get a map for folder ID to folder width
925 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
926 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
927 + " GROUP BY container;",
928 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
929
930 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800931 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
932 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800933 new Object[] {c.getLong(1) + 1, c.getLong(0)});
934 }
935
936 c.close();
937 db.setTransactionSuccessful();
938 } catch (SQLException ex) {
939 // Old version remains, which means we wipe old data
940 Log.e(TAG, ex.getMessage(), ex);
941 return false;
942 } finally {
943 db.endTransaction();
944 }
945 return true;
946 }
947
Kenny Guyed131872014-04-30 03:02:21 +0100948 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700949 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
950 // Default to the serial number of this user, for older
951 // shortcuts.
952 long userSerialNumber = userManager.getSerialNumberForUser(
953 UserHandleCompat.myUserHandle());
954 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
955 }
956
957 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100958 db.beginTransaction();
959 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700960 db.execSQL("ALTER TABLE favorites ADD COLUMN "
961 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100962 db.setTransactionSuccessful();
963 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100964 Log.e(TAG, ex.getMessage(), ex);
965 return false;
966 } finally {
967 db.endTransaction();
968 }
969 return true;
970 }
971
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700972 // Generates a new ID to use for an object in your database. This method should be only
973 // called from the main UI thread. As an exception, we do call it when we call the
974 // constructor from the worker thread; however, this doesn't extend until after the
975 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
976 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700977 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700978 public long generateNewItemId() {
979 if (mMaxItemId < 0) {
980 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700981 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700982 mMaxItemId += 1;
983 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700984 }
985
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700986 @Override
987 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
988 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
989 }
990
Chris Wren5dee7af2013-12-20 17:22:11 -0500991 public void checkId(String table, ContentValues values) {
992 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
993 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
994 mMaxScreenId = Math.max(id, mMaxScreenId);
995 } else {
996 mMaxItemId = Math.max(id, mMaxItemId);
997 }
998 }
999
Adam Cohendcd297f2013-06-18 13:13:40 -07001000 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001001 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 }
1003
1004 // Generates a new ID to use for an workspace screen in your database. This method
1005 // should be only called from the main UI thread. As an exception, we do call it when we
1006 // call the constructor from the worker thread; however, this doesn't extend until after the
1007 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1008 // after that point
1009 public long generateNewScreenId() {
1010 if (mMaxScreenId < 0) {
1011 throw new RuntimeException("Error: max screen id was not initialized");
1012 }
1013 mMaxScreenId += 1;
1014 return mMaxScreenId;
1015 }
1016
Adam Cohendcd297f2013-06-18 13:13:40 -07001017 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001018 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001019 }
1020
Adam Cohen091440a2015-03-18 14:16:05 -07001021 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001022 // 1. Ensure that externally added items have a valid item id
1023 long id = generateNewItemId();
1024 values.put(LauncherSettings.Favorites._ID, id);
1025
1026 // 2. In the case of an app widget, and if no app widget id is specified, we
1027 // attempt allocate and bind the widget.
1028 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1029 if (itemType != null &&
1030 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1031 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1032
1033 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1034 ComponentName cn = ComponentName.unflattenFromString(
1035 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1036
1037 if (cn != null) {
1038 try {
1039 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001040 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001041 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001042 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001043 }
1044 } catch (RuntimeException e) {
1045 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001046 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001047 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001048 } else {
1049 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001050 }
1051 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001052
1053 // Add screen id if not present
1054 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1055 if (!addScreenIdIfNecessary(screenId)) {
1056 return false;
1057 }
Adam Cohena043fa82014-07-23 14:49:38 -07001058 return true;
1059 }
1060
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001061 // Returns true of screen id exists, or if successfully added
1062 private boolean addScreenIdIfNecessary(long screenId) {
1063 if (!hasScreenId(screenId)) {
1064 int rank = getMaxScreenRank() + 1;
1065
1066 ContentValues v = new ContentValues();
1067 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1068 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1069 if (dbInsertAndCheck(this, getWritableDatabase(),
1070 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1071 return false;
1072 }
1073 }
1074 return true;
1075 }
1076
1077 private boolean hasScreenId(long screenId) {
1078 SQLiteDatabase db = getWritableDatabase();
1079 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1080 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1081 if (c != null) {
1082 int count = c.getCount();
1083 c.close();
1084 return count > 0;
1085 } else {
1086 return false;
1087 }
1088 }
1089
1090 private int getMaxScreenRank() {
1091 SQLiteDatabase db = getWritableDatabase();
1092 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1093 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1094
1095 // get the result
1096 final int maxRankIndex = 0;
1097 int rank = -1;
1098 if (c != null && c.moveToNext()) {
1099 rank = c.getInt(maxRankIndex);
1100 }
1101 if (c != null) {
1102 c.close();
1103 }
1104
1105 return rank;
1106 }
1107
Adam Cohen091440a2015-03-18 14:16:05 -07001108 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001109 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001110 // TODO: Use multiple loaders with fall-back and transaction.
1111 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001112
1113 // Add the screens specified by the items above
1114 Collections.sort(screenIds);
1115 int rank = 0;
1116 ContentValues values = new ContentValues();
1117 for (Long id : screenIds) {
1118 values.clear();
1119 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1120 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1121 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1122 throw new RuntimeException("Failed initialize screen table"
1123 + "from default layout");
1124 }
1125 rank++;
1126 }
1127
1128 // Ensure that the max ids are initialized
1129 mMaxItemId = initializeMaxItemId(db);
1130 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001131
Adam Cohen71483f42014-05-15 14:04:01 -07001132 return count;
1133 }
1134
Adam Cohen091440a2015-03-18 14:16:05 -07001135 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001136 final ContentResolver resolver = mContext.getContentResolver();
1137 Cursor c = null;
1138 int count = 0;
1139 int curScreen = 0;
1140
1141 try {
1142 c = resolver.query(uri, null, null, null, "title ASC");
1143 } catch (Exception e) {
1144 // Ignore
1145 }
1146
Dan Sandlerd5024042014-01-09 15:01:33 -05001147 // We already have a favorites database in the old provider
1148 if (c != null) {
1149 try {
1150 if (c.getCount() > 0) {
1151 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1152 final int intentIndex
1153 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1154 final int titleIndex
1155 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1156 final int iconTypeIndex
1157 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1158 final int iconIndex
1159 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1160 final int iconPackageIndex
1161 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1162 final int iconResourceIndex
1163 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1164 final int containerIndex
1165 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1166 final int itemTypeIndex
1167 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1168 final int screenIndex
1169 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1170 final int cellXIndex
1171 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1172 final int cellYIndex
1173 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001174 final int profileIndex
1175 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001176
1177 int i = 0;
1178 int curX = 0;
1179 int curY = 0;
1180
1181 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001182 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1183 final int width = (int) profile.numColumns;
1184 final int height = (int) profile.numRows;
1185 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001186
1187 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1188
Adam Cohen72960972014-01-15 18:13:55 -08001189 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1190 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001191 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001192
1193 while (c.moveToNext()) {
1194 final int itemType = c.getInt(itemTypeIndex);
1195 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1196 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1197 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1198 continue;
1199 }
1200
1201 final int cellX = c.getInt(cellXIndex);
1202 final int cellY = c.getInt(cellYIndex);
1203 final int screen = c.getInt(screenIndex);
1204 int container = c.getInt(containerIndex);
1205 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001206
1207 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1208 UserHandleCompat userHandle;
1209 final long userSerialNumber;
1210 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1211 userSerialNumber = c.getInt(profileIndex);
1212 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1213 } else {
1214 // Default to the serial number of this user, for older
1215 // shortcuts.
1216 userHandle = UserHandleCompat.myUserHandle();
1217 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1218 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001219
1220 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001221 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001222 continue;
1223 }
1224
Dan Sandlerd5024042014-01-09 15:01:33 -05001225 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001226
1227 final Intent intent;
1228 final ComponentName cn;
1229 try {
1230 intent = Intent.parseUri(intentStr, 0);
1231 } catch (URISyntaxException e) {
1232 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001233 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001234 continue;
1235 }
1236
1237 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001238 if (TextUtils.isEmpty(intentStr)) {
1239 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001240 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001241 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001242 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001243 !LauncherModel.isValidPackageActivity(mContext, cn,
1244 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001245 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001246 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001247 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001248 } else if (container ==
1249 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1250 // Dedupe icons directly on the workspace
1251
Adam Cohen556f6132014-01-15 15:18:08 -08001252 // Canonicalize
1253 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001254 // does not, so we clear that out to keep them the same.
1255 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001256 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001257 int flags = intent.getFlags();
1258 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001259 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001260 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001261 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001262 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001263 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001264 } else {
1265 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001266 }
1267 }
1268 }
1269
1270 ContentValues values = new ContentValues(c.getColumnCount());
1271 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1272 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1273 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1274 values.put(LauncherSettings.Favorites.ICON_TYPE,
1275 c.getInt(iconTypeIndex));
1276 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1277 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1278 c.getString(iconPackageIndex));
1279 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1280 c.getString(iconResourceIndex));
1281 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1282 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001283 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001284
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001285 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1286 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001287 }
1288
1289 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1290 // In a folder or in the hotseat, preserve position
1291 values.put(LauncherSettings.Favorites.SCREEN, screen);
1292 values.put(LauncherSettings.Favorites.CELLX, cellX);
1293 values.put(LauncherSettings.Favorites.CELLY, cellY);
1294 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001295 // For items contained directly on one of the workspace screen,
1296 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001297 }
1298
1299 values.put(LauncherSettings.Favorites.CONTAINER, container);
1300
Adam Cohen72960972014-01-15 18:13:55 -08001301 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1302 shortcuts.add(values);
1303 } else {
1304 folders.add(values);
1305 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001306 }
1307
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001308 // Now that we have all the hotseat icons, let's go through them left-right
1309 // and assign valid locations for them in the new hotseat
1310 final int N = hotseat.size();
1311 for (int idx=0; idx<N; idx++) {
1312 int hotseatX = hotseat.keyAt(idx);
1313 ContentValues values = hotseat.valueAt(idx);
1314
Adam Cohen2e6da152015-05-06 11:42:25 -07001315 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001316 // let's drop this in the next available hole in the hotseat
1317 while (++hotseatX < hotseatWidth) {
1318 if (hotseat.get(hotseatX) == null) {
1319 // found a spot! move it here
1320 values.put(LauncherSettings.Favorites.SCREEN,
1321 hotseatX);
1322 break;
1323 }
1324 }
1325 }
1326 if (hotseatX >= hotseatWidth) {
1327 // no room for you in the hotseat? it's off to the desktop with you
1328 values.put(LauncherSettings.Favorites.CONTAINER,
1329 Favorites.CONTAINER_DESKTOP);
1330 }
1331 }
1332
Adam Cohen72960972014-01-15 18:13:55 -08001333 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1334 // Folders first
1335 allItems.addAll(folders);
1336 // Then shortcuts
1337 allItems.addAll(shortcuts);
1338
1339 // Layout all the folders
1340 for (ContentValues values: allItems) {
1341 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1342 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1343 // Hotseat items and folder items have already had their
1344 // location information set. Nothing to be done here.
1345 continue;
1346 }
1347 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1348 values.put(LauncherSettings.Favorites.CELLX, curX);
1349 values.put(LauncherSettings.Favorites.CELLY, curY);
1350 curX = (curX + 1) % width;
1351 if (curX == 0) {
1352 curY = (curY + 1);
1353 }
1354 // Leave the last row of icons blank on every screen
1355 if (curY == height - 1) {
1356 curScreen = (int) generateNewScreenId();
1357 curY = 0;
1358 }
1359 }
1360
1361 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001362 db.beginTransaction();
1363 try {
Adam Cohen72960972014-01-15 18:13:55 -08001364 for (ContentValues row: allItems) {
1365 if (row == null) continue;
1366 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001367 < 0) {
1368 return;
1369 } else {
1370 count++;
1371 }
1372 }
1373 db.setTransactionSuccessful();
1374 } finally {
1375 db.endTransaction();
1376 }
1377 }
1378
1379 db.beginTransaction();
1380 try {
1381 for (i=0; i<=curScreen; i++) {
1382 final ContentValues values = new ContentValues();
1383 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1384 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1385 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1386 < 0) {
1387 return;
1388 }
1389 }
1390 db.setTransactionSuccessful();
1391 } finally {
1392 db.endTransaction();
1393 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001394
1395 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001396 }
1397 } finally {
1398 c.close();
1399 }
1400 }
1401
Sunny Goyala1365452015-10-01 15:46:24 -07001402 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1403 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001404
1405 // ensure that new screens are created to hold these icons
1406 setFlagJustLoadedOldDb();
1407
1408 // Update max IDs; very important since we just grabbed IDs from another database
1409 mMaxItemId = initializeMaxItemId(db);
1410 mMaxScreenId = initializeMaxScreenId(db);
1411 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1412 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001413 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001414
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001415 /**
1416 * @return the max _id in the provided table.
1417 */
Adam Cohen091440a2015-03-18 14:16:05 -07001418 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001419 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1420 // get the result
1421 long id = -1;
1422 if (c != null && c.moveToNext()) {
1423 id = c.getLong(0);
1424 }
1425 if (c != null) {
1426 c.close();
1427 }
1428
1429 if (id == -1) {
1430 throw new RuntimeException("Error: could not query max id in " + table);
1431 }
1432
1433 return id;
1434 }
1435
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001436 static class SqlArguments {
1437 public final String table;
1438 public final String where;
1439 public final String[] args;
1440
1441 SqlArguments(Uri url, String where, String[] args) {
1442 if (url.getPathSegments().size() == 1) {
1443 this.table = url.getPathSegments().get(0);
1444 this.where = where;
1445 this.args = args;
1446 } else if (url.getPathSegments().size() != 2) {
1447 throw new IllegalArgumentException("Invalid URI: " + url);
1448 } else if (!TextUtils.isEmpty(where)) {
1449 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1450 } else {
1451 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001452 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001453 this.args = null;
1454 }
1455 }
1456
1457 SqlArguments(Uri url) {
1458 if (url.getPathSegments().size() == 1) {
1459 table = url.getPathSegments().get(0);
1460 where = null;
1461 args = null;
1462 } else {
1463 throw new IllegalArgumentException("Invalid URI: " + url);
1464 }
1465 }
1466 }
Adam Cohen72960972014-01-15 18:13:55 -08001467}