blob: 792605fc98ec93c51027683758b7f8cacaa796d7 [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();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800268 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
269 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
270 Utilities.isAllowRotationPrefEnabled(getContext()));
271 } else {
272 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
273 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
274 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
275 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700276 return result;
277 }
278 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
279 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700280 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700281 synchronized (LISTENER_LOCK) {
282 if (mListener != null) {
283 mListener.onSettingsChanged(arg, value);
284 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700285 }
Sunny Goyalb171e562016-01-21 16:41:54 -0800286 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
287 LauncherBackupAgentHelper.dataChanged(getContext());
288 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700289 Bundle result = new Bundle();
290 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
291 return result;
292 }
Sunny Goyald2497482015-09-22 18:24:19 -0700293 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
294 clearFlagEmptyDbCreated();
295 return null;
296 }
297 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
298 Bundle result = new Bundle();
299 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
300 return result;
301 }
302 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
303 Bundle result = new Bundle();
304 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
305 return result;
306 }
307 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
308 Bundle result = new Bundle();
309 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
310 return result;
311 }
312 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
313 createEmptyDB();
314 return null;
315 }
316 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
317 loadDefaultFavoritesIfNecessary();
318 return null;
319 }
320 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
321 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
322 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
323 return null;
324 }
325 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
326 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
327 return null;
328 }
329 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
330 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
331 return null;
332 }
333 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800334 // Are you sure? (y/n)
335 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700336 return null;
337 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700338 }
339 return null;
340 }
341
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700342 /**
343 * Deletes any empty folder from the DB.
344 * @return Ids of deleted folders.
345 */
Sunny Goyald2497482015-09-22 18:24:19 -0700346 private ArrayList<Long> deleteEmptyFolders() {
347 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700348 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
349 db.beginTransaction();
350 try {
351 // Select folders whose id do not match any container value.
352 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
353 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
354 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
355 LauncherSettings.Favorites.CONTAINER + " FROM "
356 + TABLE_FAVORITES + ")";
357 Cursor c = db.query(TABLE_FAVORITES,
358 new String[] {LauncherSettings.Favorites._ID},
359 selection, null, null, null, null);
360 while (c.moveToNext()) {
361 folderIds.add(c.getLong(0));
362 }
363 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700364 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700365 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
366 LauncherSettings.Favorites._ID, folderIds), null);
367 }
368 db.setTransactionSuccessful();
369 } catch (SQLException ex) {
370 Log.e(TAG, ex.getMessage(), ex);
371 folderIds.clear();
372 } finally {
373 db.endTransaction();
374 }
375 return folderIds;
376 }
377
Sunny Goyalf076eae2016-01-11 12:25:10 -0800378 /**
379 * Overridden in tests
380 */
381 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400382 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400383 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700384 synchronized (LISTENER_LOCK) {
385 if (mListener != null) {
386 mListener.onLauncherProviderChange();
387 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700388 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400389 }
390
Adam Cohen091440a2015-03-18 14:16:05 -0700391 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400392 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800393 }
394
Brian Muramatsu5524b492012-10-02 16:55:54 -0700395 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700396 * Clears all the data for a fresh start.
397 */
Sunny Goyald2497482015-09-22 18:24:19 -0700398 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700399 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
400 }
401
Sunny Goyald2497482015-09-22 18:24:19 -0700402 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700403 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700404 }
405
Sunny Goyal42de82f2014-09-26 22:09:29 -0700406 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700407 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700408 * 1) From the app restrictions
409 * 2) From a package provided by play store
410 * 3) From a partner configuration APK, already in the system image
411 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700412 */
Sunny Goyald2497482015-09-22 18:24:19 -0700413 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700414 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700415
Winson Chungc763c4e2013-07-19 13:49:06 -0700416 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500417 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200418
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700419 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
420 if (loader == null) {
421 loader = AutoInstallsLayout.get(getContext(),
422 mOpenHelper.mAppWidgetHost, mOpenHelper);
423 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700424 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700425 final Partner partner = Partner.get(getContext().getPackageManager());
426 if (partner != null && partner.hasDefaultLayout()) {
427 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700428 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700429 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700430 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700431 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
432 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700433 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700434 }
435 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700436
Sunny Goyal9d219682014-10-23 14:21:02 -0700437 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700438 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700439 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700440 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800441
442 // There might be some partially restored DB items, due to buggy restore logic in
443 // previous versions of launcher.
444 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700445 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700446 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
447 && usingExternallyProvidedLayout) {
448 // Unable to load external layout. Cleanup and load the internal layout.
449 createEmptyDB();
450 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
451 getDefaultLayoutParser());
452 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700453 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700454 }
455 }
456
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700457 /**
458 * Creates workspace loader from an XML resource listed in the app restrictions.
459 *
460 * @return the loader if the restrictions are set and the resource exists; null otherwise.
461 */
462 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
463 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
464 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700465 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700466 return null;
467 }
468
469 Context ctx = getContext();
470 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
471 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700472 if (bundle == null) {
473 return null;
474 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700475
Sunny Goyal35ca8732015-04-06 10:45:31 -0700476 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700477 if (packageName != null) {
478 try {
479 Resources targetResources = ctx.getPackageManager()
480 .getResourcesForApplication(packageName);
481 return AutoInstallsLayout.get(ctx, packageName, targetResources,
482 mOpenHelper.mAppWidgetHost, mOpenHelper);
483 } catch (NameNotFoundException e) {
484 Log.e(TAG, "Target package for restricted profile not found", e);
485 return null;
486 }
487 }
488 return null;
489 }
490
Sunny Goyal9d219682014-10-23 14:21:02 -0700491 private DefaultLayoutParser getDefaultLayoutParser() {
492 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700493 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700494 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
495 mOpenHelper, getContext().getResources(), defaultLayout);
496 }
497
Sunny Goyald3849d12015-10-29 10:28:32 -0700498 /**
499 * Send notification that we've deleted the {@link AppWidgetHost},
500 * probably as part of the initial database creation. The receiver may
501 * want to re-call {@link AppWidgetHost#startListening()} to ensure
502 * callbacks are correctly set.
503 */
504 @Thunk void notifyAppHostReset() {
505 new MainThreadExecutor().execute(new Runnable() {
506
507 @Override
508 public void run() {
509 synchronized (LISTENER_LOCK) {
510 if (mListener != null) {
511 mListener.onAppWidgetHostReset();
512 }
513 }
514 }
515 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500516 }
517
Sunny Goyalf076eae2016-01-11 12:25:10 -0800518 /**
519 * The class is subclassed in tests to create an in-memory db.
520 */
521 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700522 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800523 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700524 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700525 private long mMaxItemId = -1;
526 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800527
Sunny Goyald3849d12015-10-29 10:28:32 -0700528 DatabaseHelper(Context context, LauncherProvider provider) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100529 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700531 mProvider = provider;
532
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700533 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700534
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700535 // Table creation sometimes fails silently, which leads to a crash loop.
536 // This way, we will try to create a table every time after crash, so the device
537 // would eventually be able to recover.
538 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
539 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
540 // This operation is a no-op if the table already exists.
541 addFavoritesTable(getWritableDatabase(), true);
542 addWorkspacesTable(getWritableDatabase(), true);
543 }
544
Winson Chung3d503fb2011-07-13 17:25:49 -0700545 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
546 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700547 if (mMaxItemId == -1) {
548 mMaxItemId = initializeMaxItemId(getWritableDatabase());
549 }
550 if (mMaxScreenId == -1) {
551 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700552 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800553 }
554
Sunny Goyalf076eae2016-01-11 12:25:10 -0800555 /**
556 * Constructor used only in tests.
557 */
558 public DatabaseHelper(Context context, LauncherProvider provider, String tableName) {
559 super(context, tableName, null, DATABASE_VERSION);
560 mContext = context;
561 mProvider = provider;
562
563 mAppWidgetHost = null;
564 mMaxItemId = initializeMaxItemId(getWritableDatabase());
565 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
566 }
567
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700568 private boolean tableExists(String tableName) {
569 Cursor c = getReadableDatabase().query(
570 true, "sqlite_master", new String[] {"tbl_name"},
571 "tbl_name = ?", new String[] {tableName},
572 null, null, null, null, null);
573 try {
574 return c.getCount() > 0;
575 } finally {
576 c.close();
577 }
578 }
579
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800580 @Override
581 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800582 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700583
Adam Cohendcd297f2013-06-18 13:13:40 -0700584 mMaxItemId = 1;
585 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700586
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700587 addFavoritesTable(db, false);
588 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700590 // Database was just created, so wipe any previous widgets
591 if (mAppWidgetHost != null) {
592 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700593 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800594 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700595
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800596 // Fresh and clean launcher DB.
597 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800598 onEmptyDbCreated();
599 }
600
601 /**
602 * Overriden in tests.
603 */
604 protected void onEmptyDbCreated() {
605 // Set the flag for empty DB
606 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700607
608 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800609 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
610 mContext);
611 }
612
613 protected long getDefaultUserSerial() {
614 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
615 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
617
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700619 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700620 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
621 "_id INTEGER PRIMARY KEY," +
622 "title TEXT," +
623 "intent TEXT," +
624 "container INTEGER," +
625 "screen INTEGER," +
626 "cellX INTEGER," +
627 "cellY INTEGER," +
628 "spanX INTEGER," +
629 "spanY INTEGER," +
630 "itemType INTEGER," +
631 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
632 "isShortcut INTEGER," +
633 "iconType INTEGER," +
634 "iconPackage TEXT," +
635 "iconResource TEXT," +
636 "icon BLOB," +
637 "uri TEXT," +
638 "displayMode INTEGER," +
639 "appWidgetProvider TEXT," +
640 "modified INTEGER NOT NULL DEFAULT 0," +
641 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800642 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 "rank INTEGER NOT NULL DEFAULT 0," +
644 "options INTEGER NOT NULL DEFAULT 0" +
645 ");");
646 }
647
648 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
649 String ifNotExists = optional ? " IF NOT EXISTS " : "";
650 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800651 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400652 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
653 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700654 ");");
655 }
656
Adam Cohen119285e2014-04-02 16:59:08 -0700657 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700658 // Delete items directly on the workspace who's screen id doesn't exist
659 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
660 // AND container = -100"
661 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
662 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700663 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700664 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
665 " AND " +
666 LauncherSettings.Favorites.CONTAINER + " = " +
667 LauncherSettings.Favorites.CONTAINER_DESKTOP;
668 db.execSQL(removeOrphanedDesktopItems);
669
670 // Delete items contained in folders which no longer exist (after above statement)
671 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
672 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
673 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
674 " WHERE " +
675 LauncherSettings.Favorites.CONTAINER + " <> " +
676 LauncherSettings.Favorites.CONTAINER_DESKTOP +
677 " AND "
678 + LauncherSettings.Favorites.CONTAINER + " <> " +
679 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
680 " AND "
681 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
682 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
683 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
684 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
685 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700686 }
687
Winson Chungc763c4e2013-07-19 13:49:06 -0700688 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700689 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700690 }
691
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800692 @Override
693 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700694 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800695 switch (oldVersion) {
696 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800697 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800698 case 12: {
699 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
700 // to persist workspace screens and their relative order.
701 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700702 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800703 }
704 case 13: {
705 db.beginTransaction();
706 try {
707 // Insert new column for holding widget provider name
708 db.execSQL("ALTER TABLE favorites " +
709 "ADD COLUMN appWidgetProvider TEXT;");
710 db.setTransactionSuccessful();
711 } catch (SQLException ex) {
712 Log.e(TAG, ex.getMessage(), ex);
713 // Old version remains, which means we wipe old data
714 break;
715 } finally {
716 db.endTransaction();
717 }
718 }
719 case 14: {
720 db.beginTransaction();
721 try {
722 // Insert new column for holding update timestamp
723 db.execSQL("ALTER TABLE favorites " +
724 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
725 db.execSQL("ALTER TABLE workspaceScreens " +
726 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
727 db.setTransactionSuccessful();
728 } catch (SQLException ex) {
729 Log.e(TAG, ex.getMessage(), ex);
730 // Old version remains, which means we wipe old data
731 break;
732 } finally {
733 db.endTransaction();
734 }
735 }
736 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700737 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 // Old version remains, which means we wipe old data
739 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800740 }
741 }
742 case 16: {
743 // We use the db version upgrade here to identify users who may not have seen
744 // clings yet (because they weren't available), but for whom the clings are now
745 // available (tablet users). Because one of the possible cling flows (migration)
746 // is very destructive (wipes out workspaces), we want to prevent this from showing
747 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800748 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800749 }
750 case 17: {
751 // No-op
752 }
753 case 18: {
754 // Due to a data loss bug, some users may have items associated with screen ids
755 // which no longer exist. Since this can cause other problems, and since the user
756 // will never see these items anyway, we use database upgrade as an opportunity to
757 // clean things up.
758 removeOrphanedItems(db);
759 }
760 case 19: {
761 // Add userId column
762 if (!addProfileColumn(db)) {
763 // Old version remains, which means we wipe old data
764 break;
765 }
766 }
767 case 20:
768 if (!updateFolderItemsRank(db, true)) {
769 break;
770 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800771 case 21:
772 // Recreate workspace table with screen id a primary key
773 if (!recreateWorkspaceTable(db)) {
774 break;
775 }
776 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700777 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
778 // Old version remains, which means we wipe old data
779 break;
780 }
781 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700782 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700783 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700784 case 24:
785 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700786 case 25:
787 convertShortcutsToLauncherActivities(db);
788 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 // DB Upgraded successfully
790 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400791 }
792 }
793
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 // DB was not upgraded
795 Log.w(TAG, "Destroying all old data.");
796 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800797 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800798
Adam Cohen9b1d0622014-05-21 19:01:57 -0700799 @Override
800 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
801 // This shouldn't happen -- throw our hands up in the air and start over.
802 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
803 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700804 createEmptyDB(db);
805 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700806
Sunny Goyal42de82f2014-09-26 22:09:29 -0700807 /**
808 * Clears all the data for a fresh start.
809 */
810 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700811 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
812 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
813 onCreate(db);
814 }
815
Sunny Goyald2f38192015-02-25 10:46:34 -0800816 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700817 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
818 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
819 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700820 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700821 db.beginTransaction();
822 Cursor c = null;
823 SQLiteStatement updateStmt = null;
824
825 try {
826 // Only consider the primary user as other users can't have a shortcut.
827 long userSerial = UserManagerCompat.getInstance(mContext)
828 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
829 c = db.query(TABLE_FAVORITES, new String[] {
830 Favorites._ID,
831 Favorites.INTENT,
832 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
833 null, null, null, null);
834
835 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
836 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
837
838 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
839 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
840
841 while (c.moveToNext()) {
842 String intentDescription = c.getString(intentIndex);
843 Intent intent;
844 try {
845 intent = Intent.parseUri(intentDescription, 0);
846 } catch (URISyntaxException e) {
847 Log.e(TAG, "Unable to parse intent", e);
848 continue;
849 }
850
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700851 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 continue;
853 }
854
855 long id = c.getLong(idIndex);
856 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700857 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700858 }
859 db.setTransactionSuccessful();
860 } catch (SQLException ex) {
861 Log.w(TAG, "Error deduping shortcuts", ex);
862 } finally {
863 db.endTransaction();
864 if (c != null) {
865 c.close();
866 }
867 if (updateStmt != null) {
868 updateStmt.close();
869 }
870 }
871 }
872
873 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800874 * Recreates workspace table and migrates data to the new table.
875 */
876 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
877 db.beginTransaction();
878 try {
879 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
880 new String[] {LauncherSettings.WorkspaceScreens._ID},
881 null, null, null, null,
882 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
883 ArrayList<Long> sortedIDs = new ArrayList<Long>();
884 long maxId = 0;
885 try {
886 while (c.moveToNext()) {
887 Long id = c.getLong(0);
888 if (!sortedIDs.contains(id)) {
889 sortedIDs.add(id);
890 maxId = Math.max(maxId, id);
891 }
892 }
893 } finally {
894 c.close();
895 }
896
897 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700898 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800899
900 // Add all screen ids back
901 int total = sortedIDs.size();
902 for (int i = 0; i < total; i++) {
903 ContentValues values = new ContentValues();
904 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
905 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
906 addModifiedTime(values);
907 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
908 }
909 db.setTransactionSuccessful();
910 mMaxScreenId = maxId;
911 } catch (SQLException ex) {
912 // Old version remains, which means we wipe old data
913 Log.e(TAG, ex.getMessage(), ex);
914 return false;
915 } finally {
916 db.endTransaction();
917 }
918 return true;
919 }
920
Adam Cohen091440a2015-03-18 14:16:05 -0700921 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800922 db.beginTransaction();
923 try {
924 if (addRankColumn) {
925 // Insert new column for holding rank
926 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
927 }
928
929 // Get a map for folder ID to folder width
930 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
931 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
932 + " GROUP BY container;",
933 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
934
935 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800936 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
937 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800938 new Object[] {c.getLong(1) + 1, c.getLong(0)});
939 }
940
941 c.close();
942 db.setTransactionSuccessful();
943 } catch (SQLException ex) {
944 // Old version remains, which means we wipe old data
945 Log.e(TAG, ex.getMessage(), ex);
946 return false;
947 } finally {
948 db.endTransaction();
949 }
950 return true;
951 }
952
Kenny Guyed131872014-04-30 03:02:21 +0100953 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700954 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
955 // Default to the serial number of this user, for older
956 // shortcuts.
957 long userSerialNumber = userManager.getSerialNumberForUser(
958 UserHandleCompat.myUserHandle());
959 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
960 }
961
962 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100963 db.beginTransaction();
964 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700965 db.execSQL("ALTER TABLE favorites ADD COLUMN "
966 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100967 db.setTransactionSuccessful();
968 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100969 Log.e(TAG, ex.getMessage(), ex);
970 return false;
971 } finally {
972 db.endTransaction();
973 }
974 return true;
975 }
976
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700977 // Generates a new ID to use for an object in your database. This method should be only
978 // called from the main UI thread. As an exception, we do call it when we call the
979 // constructor from the worker thread; however, this doesn't extend until after the
980 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
981 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700982 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 public long generateNewItemId() {
984 if (mMaxItemId < 0) {
985 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700986 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700987 mMaxItemId += 1;
988 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700989 }
990
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700991 @Override
992 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
993 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
994 }
995
Chris Wren5dee7af2013-12-20 17:22:11 -0500996 public void checkId(String table, ContentValues values) {
997 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
998 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
999 mMaxScreenId = Math.max(id, mMaxScreenId);
1000 } else {
1001 mMaxItemId = Math.max(id, mMaxItemId);
1002 }
1003 }
1004
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001006 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 }
1008
1009 // Generates a new ID to use for an workspace screen in your database. This method
1010 // should be only called from the main UI thread. As an exception, we do call it when we
1011 // call the constructor from the worker thread; however, this doesn't extend until after the
1012 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1013 // after that point
1014 public long generateNewScreenId() {
1015 if (mMaxScreenId < 0) {
1016 throw new RuntimeException("Error: max screen id was not initialized");
1017 }
1018 mMaxScreenId += 1;
1019 return mMaxScreenId;
1020 }
1021
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001023 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001024 }
1025
Adam Cohen091440a2015-03-18 14:16:05 -07001026 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001027 // 1. Ensure that externally added items have a valid item id
1028 long id = generateNewItemId();
1029 values.put(LauncherSettings.Favorites._ID, id);
1030
1031 // 2. In the case of an app widget, and if no app widget id is specified, we
1032 // attempt allocate and bind the widget.
1033 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1034 if (itemType != null &&
1035 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1036 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1037
1038 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1039 ComponentName cn = ComponentName.unflattenFromString(
1040 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1041
1042 if (cn != null) {
1043 try {
1044 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001045 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001046 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001047 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001048 }
1049 } catch (RuntimeException e) {
1050 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001051 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001052 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001053 } else {
1054 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001055 }
1056 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001057
1058 // Add screen id if not present
1059 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1060 if (!addScreenIdIfNecessary(screenId)) {
1061 return false;
1062 }
Adam Cohena043fa82014-07-23 14:49:38 -07001063 return true;
1064 }
1065
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001066 // Returns true of screen id exists, or if successfully added
1067 private boolean addScreenIdIfNecessary(long screenId) {
1068 if (!hasScreenId(screenId)) {
1069 int rank = getMaxScreenRank() + 1;
1070
1071 ContentValues v = new ContentValues();
1072 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1073 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1074 if (dbInsertAndCheck(this, getWritableDatabase(),
1075 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1076 return false;
1077 }
1078 }
1079 return true;
1080 }
1081
1082 private boolean hasScreenId(long screenId) {
1083 SQLiteDatabase db = getWritableDatabase();
1084 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1085 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1086 if (c != null) {
1087 int count = c.getCount();
1088 c.close();
1089 return count > 0;
1090 } else {
1091 return false;
1092 }
1093 }
1094
1095 private int getMaxScreenRank() {
1096 SQLiteDatabase db = getWritableDatabase();
1097 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1098 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1099
1100 // get the result
1101 final int maxRankIndex = 0;
1102 int rank = -1;
1103 if (c != null && c.moveToNext()) {
1104 rank = c.getInt(maxRankIndex);
1105 }
1106 if (c != null) {
1107 c.close();
1108 }
1109
1110 return rank;
1111 }
1112
Adam Cohen091440a2015-03-18 14:16:05 -07001113 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001114 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001115 // TODO: Use multiple loaders with fall-back and transaction.
1116 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001117
1118 // Add the screens specified by the items above
1119 Collections.sort(screenIds);
1120 int rank = 0;
1121 ContentValues values = new ContentValues();
1122 for (Long id : screenIds) {
1123 values.clear();
1124 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1125 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1126 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1127 throw new RuntimeException("Failed initialize screen table"
1128 + "from default layout");
1129 }
1130 rank++;
1131 }
1132
1133 // Ensure that the max ids are initialized
1134 mMaxItemId = initializeMaxItemId(db);
1135 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001136
Adam Cohen71483f42014-05-15 14:04:01 -07001137 return count;
1138 }
1139
Adam Cohen091440a2015-03-18 14:16:05 -07001140 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001141 final ContentResolver resolver = mContext.getContentResolver();
1142 Cursor c = null;
1143 int count = 0;
1144 int curScreen = 0;
1145
1146 try {
1147 c = resolver.query(uri, null, null, null, "title ASC");
1148 } catch (Exception e) {
1149 // Ignore
1150 }
1151
Dan Sandlerd5024042014-01-09 15:01:33 -05001152 // We already have a favorites database in the old provider
1153 if (c != null) {
1154 try {
1155 if (c.getCount() > 0) {
1156 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1157 final int intentIndex
1158 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1159 final int titleIndex
1160 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1161 final int iconTypeIndex
1162 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1163 final int iconIndex
1164 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1165 final int iconPackageIndex
1166 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1167 final int iconResourceIndex
1168 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1169 final int containerIndex
1170 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1171 final int itemTypeIndex
1172 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1173 final int screenIndex
1174 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1175 final int cellXIndex
1176 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1177 final int cellYIndex
1178 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001179 final int profileIndex
1180 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001181
1182 int i = 0;
1183 int curX = 0;
1184 int curY = 0;
1185
1186 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001187 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1188 final int width = (int) profile.numColumns;
1189 final int height = (int) profile.numRows;
1190 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001191
1192 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1193
Adam Cohen72960972014-01-15 18:13:55 -08001194 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1195 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001196 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001197
1198 while (c.moveToNext()) {
1199 final int itemType = c.getInt(itemTypeIndex);
1200 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1201 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1202 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1203 continue;
1204 }
1205
1206 final int cellX = c.getInt(cellXIndex);
1207 final int cellY = c.getInt(cellYIndex);
1208 final int screen = c.getInt(screenIndex);
1209 int container = c.getInt(containerIndex);
1210 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001211
1212 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1213 UserHandleCompat userHandle;
1214 final long userSerialNumber;
1215 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1216 userSerialNumber = c.getInt(profileIndex);
1217 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1218 } else {
1219 // Default to the serial number of this user, for older
1220 // shortcuts.
1221 userHandle = UserHandleCompat.myUserHandle();
1222 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1223 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001224
1225 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001226 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001227 continue;
1228 }
1229
Dan Sandlerd5024042014-01-09 15:01:33 -05001230 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001231
1232 final Intent intent;
1233 final ComponentName cn;
1234 try {
1235 intent = Intent.parseUri(intentStr, 0);
1236 } catch (URISyntaxException e) {
1237 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001238 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001239 continue;
1240 }
1241
1242 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001243 if (TextUtils.isEmpty(intentStr)) {
1244 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001245 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001246 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001247 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001248 !LauncherModel.isValidPackageActivity(mContext, cn,
1249 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001250 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001251 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001252 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001253 } else if (container ==
1254 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1255 // Dedupe icons directly on the workspace
1256
Adam Cohen556f6132014-01-15 15:18:08 -08001257 // Canonicalize
1258 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001259 // does not, so we clear that out to keep them the same.
1260 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001261 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001262 int flags = intent.getFlags();
1263 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001264 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001265 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001266 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001267 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001268 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001269 } else {
1270 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001271 }
1272 }
1273 }
1274
1275 ContentValues values = new ContentValues(c.getColumnCount());
1276 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1277 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1278 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1279 values.put(LauncherSettings.Favorites.ICON_TYPE,
1280 c.getInt(iconTypeIndex));
1281 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1282 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1283 c.getString(iconPackageIndex));
1284 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1285 c.getString(iconResourceIndex));
1286 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1287 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001288 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001289
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001290 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1291 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001292 }
1293
1294 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1295 // In a folder or in the hotseat, preserve position
1296 values.put(LauncherSettings.Favorites.SCREEN, screen);
1297 values.put(LauncherSettings.Favorites.CELLX, cellX);
1298 values.put(LauncherSettings.Favorites.CELLY, cellY);
1299 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001300 // For items contained directly on one of the workspace screen,
1301 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001302 }
1303
1304 values.put(LauncherSettings.Favorites.CONTAINER, container);
1305
Adam Cohen72960972014-01-15 18:13:55 -08001306 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1307 shortcuts.add(values);
1308 } else {
1309 folders.add(values);
1310 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001311 }
1312
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001313 // Now that we have all the hotseat icons, let's go through them left-right
1314 // and assign valid locations for them in the new hotseat
1315 final int N = hotseat.size();
1316 for (int idx=0; idx<N; idx++) {
1317 int hotseatX = hotseat.keyAt(idx);
1318 ContentValues values = hotseat.valueAt(idx);
1319
Adam Cohen2e6da152015-05-06 11:42:25 -07001320 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001321 // let's drop this in the next available hole in the hotseat
1322 while (++hotseatX < hotseatWidth) {
1323 if (hotseat.get(hotseatX) == null) {
1324 // found a spot! move it here
1325 values.put(LauncherSettings.Favorites.SCREEN,
1326 hotseatX);
1327 break;
1328 }
1329 }
1330 }
1331 if (hotseatX >= hotseatWidth) {
1332 // no room for you in the hotseat? it's off to the desktop with you
1333 values.put(LauncherSettings.Favorites.CONTAINER,
1334 Favorites.CONTAINER_DESKTOP);
1335 }
1336 }
1337
Adam Cohen72960972014-01-15 18:13:55 -08001338 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1339 // Folders first
1340 allItems.addAll(folders);
1341 // Then shortcuts
1342 allItems.addAll(shortcuts);
1343
1344 // Layout all the folders
1345 for (ContentValues values: allItems) {
1346 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1347 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1348 // Hotseat items and folder items have already had their
1349 // location information set. Nothing to be done here.
1350 continue;
1351 }
1352 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1353 values.put(LauncherSettings.Favorites.CELLX, curX);
1354 values.put(LauncherSettings.Favorites.CELLY, curY);
1355 curX = (curX + 1) % width;
1356 if (curX == 0) {
1357 curY = (curY + 1);
1358 }
1359 // Leave the last row of icons blank on every screen
1360 if (curY == height - 1) {
1361 curScreen = (int) generateNewScreenId();
1362 curY = 0;
1363 }
1364 }
1365
1366 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001367 db.beginTransaction();
1368 try {
Adam Cohen72960972014-01-15 18:13:55 -08001369 for (ContentValues row: allItems) {
1370 if (row == null) continue;
1371 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001372 < 0) {
1373 return;
1374 } else {
1375 count++;
1376 }
1377 }
1378 db.setTransactionSuccessful();
1379 } finally {
1380 db.endTransaction();
1381 }
1382 }
1383
1384 db.beginTransaction();
1385 try {
1386 for (i=0; i<=curScreen; i++) {
1387 final ContentValues values = new ContentValues();
1388 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1389 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1390 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1391 < 0) {
1392 return;
1393 }
1394 }
1395 db.setTransactionSuccessful();
1396 } finally {
1397 db.endTransaction();
1398 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001399
1400 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001401 }
1402 } finally {
1403 c.close();
1404 }
1405 }
1406
Sunny Goyala1365452015-10-01 15:46:24 -07001407 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1408 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001409
1410 // ensure that new screens are created to hold these icons
1411 setFlagJustLoadedOldDb();
1412
1413 // Update max IDs; very important since we just grabbed IDs from another database
1414 mMaxItemId = initializeMaxItemId(db);
1415 mMaxScreenId = initializeMaxScreenId(db);
1416 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1417 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001418 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001419
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001420 /**
1421 * @return the max _id in the provided table.
1422 */
Adam Cohen091440a2015-03-18 14:16:05 -07001423 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001424 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1425 // get the result
1426 long id = -1;
1427 if (c != null && c.moveToNext()) {
1428 id = c.getLong(0);
1429 }
1430 if (c != null) {
1431 c.close();
1432 }
1433
1434 if (id == -1) {
1435 throw new RuntimeException("Error: could not query max id in " + table);
1436 }
1437
1438 return id;
1439 }
1440
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001441 static class SqlArguments {
1442 public final String table;
1443 public final String where;
1444 public final String[] args;
1445
1446 SqlArguments(Uri url, String where, String[] args) {
1447 if (url.getPathSegments().size() == 1) {
1448 this.table = url.getPathSegments().get(0);
1449 this.where = where;
1450 this.args = args;
1451 } else if (url.getPathSegments().size() != 2) {
1452 throw new IllegalArgumentException("Invalid URI: " + url);
1453 } else if (!TextUtils.isEmpty(where)) {
1454 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1455 } else {
1456 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001457 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001458 this.args = null;
1459 }
1460 }
1461
1462 SqlArguments(Uri url) {
1463 if (url.getPathSegments().size() == 1) {
1464 table = url.getPathSegments().get(0);
1465 where = null;
1466 args = null;
1467 } else {
1468 throw new IllegalArgumentException("Invalid URI: " + url);
1469 }
1470 }
1471 }
Adam Cohen72960972014-01-15 18:13:55 -08001472}