blob: ac9b32168ade4d4c928a2d22df68b63311ea0bb4 [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 }
281 Bundle result = new Bundle();
282 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
283 return result;
284 }
Sunny Goyald2497482015-09-22 18:24:19 -0700285 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
286 clearFlagEmptyDbCreated();
287 return null;
288 }
289 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
290 Bundle result = new Bundle();
291 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
292 return result;
293 }
294 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
295 Bundle result = new Bundle();
296 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
297 return result;
298 }
299 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
300 Bundle result = new Bundle();
301 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
302 return result;
303 }
304 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
305 createEmptyDB();
306 return null;
307 }
308 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
309 loadDefaultFavoritesIfNecessary();
310 return null;
311 }
312 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
313 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
314 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
315 return null;
316 }
317 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
318 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
319 return null;
320 }
321 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
322 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
323 return null;
324 }
325 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800326 // Are you sure? (y/n)
327 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700328 return null;
329 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700330 }
331 return null;
332 }
333
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700334 /**
335 * Deletes any empty folder from the DB.
336 * @return Ids of deleted folders.
337 */
Sunny Goyald2497482015-09-22 18:24:19 -0700338 private ArrayList<Long> deleteEmptyFolders() {
339 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700340 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
341 db.beginTransaction();
342 try {
343 // Select folders whose id do not match any container value.
344 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
345 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
346 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
347 LauncherSettings.Favorites.CONTAINER + " FROM "
348 + TABLE_FAVORITES + ")";
349 Cursor c = db.query(TABLE_FAVORITES,
350 new String[] {LauncherSettings.Favorites._ID},
351 selection, null, null, null, null);
352 while (c.moveToNext()) {
353 folderIds.add(c.getLong(0));
354 }
355 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700356 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700357 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
358 LauncherSettings.Favorites._ID, folderIds), null);
359 }
360 db.setTransactionSuccessful();
361 } catch (SQLException ex) {
362 Log.e(TAG, ex.getMessage(), ex);
363 folderIds.clear();
364 } finally {
365 db.endTransaction();
366 }
367 return folderIds;
368 }
369
Sunny Goyalf076eae2016-01-11 12:25:10 -0800370 /**
371 * Overridden in tests
372 */
373 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400374 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400375 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700376 synchronized (LISTENER_LOCK) {
377 if (mListener != null) {
378 mListener.onLauncherProviderChange();
379 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700380 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400381 }
382
Adam Cohen091440a2015-03-18 14:16:05 -0700383 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400384 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800385 }
386
Brian Muramatsu5524b492012-10-02 16:55:54 -0700387 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700388 * Clears all the data for a fresh start.
389 */
Sunny Goyald2497482015-09-22 18:24:19 -0700390 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700391 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
392 }
393
Sunny Goyald2497482015-09-22 18:24:19 -0700394 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700395 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700396 }
397
Sunny Goyal42de82f2014-09-26 22:09:29 -0700398 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700399 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700400 * 1) From the app restrictions
401 * 2) From a package provided by play store
402 * 3) From a partner configuration APK, already in the system image
403 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700404 */
Sunny Goyald2497482015-09-22 18:24:19 -0700405 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700406 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700407
Winson Chungc763c4e2013-07-19 13:49:06 -0700408 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500409 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200410
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700411 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
412 if (loader == null) {
413 loader = AutoInstallsLayout.get(getContext(),
414 mOpenHelper.mAppWidgetHost, mOpenHelper);
415 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700416 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700417 final Partner partner = Partner.get(getContext().getPackageManager());
418 if (partner != null && partner.hasDefaultLayout()) {
419 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700420 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700421 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700422 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700423 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
424 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700425 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700426 }
427 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700428
Sunny Goyal9d219682014-10-23 14:21:02 -0700429 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700430 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700431 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700432 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800433
434 // There might be some partially restored DB items, due to buggy restore logic in
435 // previous versions of launcher.
436 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700437 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700438 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
439 && usingExternallyProvidedLayout) {
440 // Unable to load external layout. Cleanup and load the internal layout.
441 createEmptyDB();
442 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
443 getDefaultLayoutParser());
444 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700445 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700446 }
447 }
448
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700449 /**
450 * Creates workspace loader from an XML resource listed in the app restrictions.
451 *
452 * @return the loader if the restrictions are set and the resource exists; null otherwise.
453 */
454 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
455 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
456 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700457 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700458 return null;
459 }
460
461 Context ctx = getContext();
462 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
463 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700464 if (bundle == null) {
465 return null;
466 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700467
Sunny Goyal35ca8732015-04-06 10:45:31 -0700468 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700469 if (packageName != null) {
470 try {
471 Resources targetResources = ctx.getPackageManager()
472 .getResourcesForApplication(packageName);
473 return AutoInstallsLayout.get(ctx, packageName, targetResources,
474 mOpenHelper.mAppWidgetHost, mOpenHelper);
475 } catch (NameNotFoundException e) {
476 Log.e(TAG, "Target package for restricted profile not found", e);
477 return null;
478 }
479 }
480 return null;
481 }
482
Sunny Goyal9d219682014-10-23 14:21:02 -0700483 private DefaultLayoutParser getDefaultLayoutParser() {
484 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700485 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700486 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
487 mOpenHelper, getContext().getResources(), defaultLayout);
488 }
489
Sunny Goyald3849d12015-10-29 10:28:32 -0700490 /**
491 * Send notification that we've deleted the {@link AppWidgetHost},
492 * probably as part of the initial database creation. The receiver may
493 * want to re-call {@link AppWidgetHost#startListening()} to ensure
494 * callbacks are correctly set.
495 */
496 @Thunk void notifyAppHostReset() {
497 new MainThreadExecutor().execute(new Runnable() {
498
499 @Override
500 public void run() {
501 synchronized (LISTENER_LOCK) {
502 if (mListener != null) {
503 mListener.onAppWidgetHostReset();
504 }
505 }
506 }
507 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500508 }
509
Sunny Goyalf076eae2016-01-11 12:25:10 -0800510 /**
511 * The class is subclassed in tests to create an in-memory db.
512 */
513 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700514 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800515 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700516 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700517 private long mMaxItemId = -1;
518 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800519
Sunny Goyald3849d12015-10-29 10:28:32 -0700520 DatabaseHelper(Context context, LauncherProvider provider) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100521 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800522 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 mProvider = provider;
524
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700525 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700526
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700527 // Table creation sometimes fails silently, which leads to a crash loop.
528 // This way, we will try to create a table every time after crash, so the device
529 // would eventually be able to recover.
530 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
531 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
532 // This operation is a no-op if the table already exists.
533 addFavoritesTable(getWritableDatabase(), true);
534 addWorkspacesTable(getWritableDatabase(), true);
535 }
536
Winson Chung3d503fb2011-07-13 17:25:49 -0700537 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
538 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700539 if (mMaxItemId == -1) {
540 mMaxItemId = initializeMaxItemId(getWritableDatabase());
541 }
542 if (mMaxScreenId == -1) {
543 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700544 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545 }
546
Sunny Goyalf076eae2016-01-11 12:25:10 -0800547 /**
548 * Constructor used only in tests.
549 */
550 public DatabaseHelper(Context context, LauncherProvider provider, String tableName) {
551 super(context, tableName, null, DATABASE_VERSION);
552 mContext = context;
553 mProvider = provider;
554
555 mAppWidgetHost = null;
556 mMaxItemId = initializeMaxItemId(getWritableDatabase());
557 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
558 }
559
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700560 private boolean tableExists(String tableName) {
561 Cursor c = getReadableDatabase().query(
562 true, "sqlite_master", new String[] {"tbl_name"},
563 "tbl_name = ?", new String[] {tableName},
564 null, null, null, null, null);
565 try {
566 return c.getCount() > 0;
567 } finally {
568 c.close();
569 }
570 }
571
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 @Override
573 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800574 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700575
Adam Cohendcd297f2013-06-18 13:13:40 -0700576 mMaxItemId = 1;
577 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700578
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700579 addFavoritesTable(db, false);
580 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800581
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700582 // Database was just created, so wipe any previous widgets
583 if (mAppWidgetHost != null) {
584 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700585 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800586 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700587
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800588 // Fresh and clean launcher DB.
589 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800590 onEmptyDbCreated();
591 }
592
593 /**
594 * Overriden in tests.
595 */
596 protected void onEmptyDbCreated() {
597 // Set the flag for empty DB
598 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700599
600 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800601 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
602 mContext);
603 }
604
605 protected long getDefaultUserSerial() {
606 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
607 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800608 }
609
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700610 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700611 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700612 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
613 "_id INTEGER PRIMARY KEY," +
614 "title TEXT," +
615 "intent TEXT," +
616 "container INTEGER," +
617 "screen INTEGER," +
618 "cellX INTEGER," +
619 "cellY INTEGER," +
620 "spanX INTEGER," +
621 "spanY INTEGER," +
622 "itemType INTEGER," +
623 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
624 "isShortcut INTEGER," +
625 "iconType INTEGER," +
626 "iconPackage TEXT," +
627 "iconResource TEXT," +
628 "icon BLOB," +
629 "uri TEXT," +
630 "displayMode INTEGER," +
631 "appWidgetProvider TEXT," +
632 "modified INTEGER NOT NULL DEFAULT 0," +
633 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800634 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700635 "rank INTEGER NOT NULL DEFAULT 0," +
636 "options INTEGER NOT NULL DEFAULT 0" +
637 ");");
638 }
639
640 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
641 String ifNotExists = optional ? " IF NOT EXISTS " : "";
642 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800643 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400644 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
645 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700646 ");");
647 }
648
Adam Cohen119285e2014-04-02 16:59:08 -0700649 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700650 // Delete items directly on the workspace who's screen id doesn't exist
651 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
652 // AND container = -100"
653 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
654 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700655 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700656 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
657 " AND " +
658 LauncherSettings.Favorites.CONTAINER + " = " +
659 LauncherSettings.Favorites.CONTAINER_DESKTOP;
660 db.execSQL(removeOrphanedDesktopItems);
661
662 // Delete items contained in folders which no longer exist (after above statement)
663 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
664 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
665 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
666 " WHERE " +
667 LauncherSettings.Favorites.CONTAINER + " <> " +
668 LauncherSettings.Favorites.CONTAINER_DESKTOP +
669 " AND "
670 + LauncherSettings.Favorites.CONTAINER + " <> " +
671 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
672 " AND "
673 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
674 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
675 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
676 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
677 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700678 }
679
Winson Chungc763c4e2013-07-19 13:49:06 -0700680 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700681 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700682 }
683
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 @Override
685 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700686 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800687 switch (oldVersion) {
688 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800689 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800690 case 12: {
691 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
692 // to persist workspace screens and their relative order.
693 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700694 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800695 }
696 case 13: {
697 db.beginTransaction();
698 try {
699 // Insert new column for holding widget provider name
700 db.execSQL("ALTER TABLE favorites " +
701 "ADD COLUMN appWidgetProvider TEXT;");
702 db.setTransactionSuccessful();
703 } catch (SQLException ex) {
704 Log.e(TAG, ex.getMessage(), ex);
705 // Old version remains, which means we wipe old data
706 break;
707 } finally {
708 db.endTransaction();
709 }
710 }
711 case 14: {
712 db.beginTransaction();
713 try {
714 // Insert new column for holding update timestamp
715 db.execSQL("ALTER TABLE favorites " +
716 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
717 db.execSQL("ALTER TABLE workspaceScreens " +
718 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
719 db.setTransactionSuccessful();
720 } catch (SQLException ex) {
721 Log.e(TAG, ex.getMessage(), ex);
722 // Old version remains, which means we wipe old data
723 break;
724 } finally {
725 db.endTransaction();
726 }
727 }
728 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700729 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800730 // Old version remains, which means we wipe old data
731 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 }
733 }
734 case 16: {
735 // We use the db version upgrade here to identify users who may not have seen
736 // clings yet (because they weren't available), but for whom the clings are now
737 // available (tablet users). Because one of the possible cling flows (migration)
738 // is very destructive (wipes out workspaces), we want to prevent this from showing
739 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800740 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800741 }
742 case 17: {
743 // No-op
744 }
745 case 18: {
746 // Due to a data loss bug, some users may have items associated with screen ids
747 // which no longer exist. Since this can cause other problems, and since the user
748 // will never see these items anyway, we use database upgrade as an opportunity to
749 // clean things up.
750 removeOrphanedItems(db);
751 }
752 case 19: {
753 // Add userId column
754 if (!addProfileColumn(db)) {
755 // Old version remains, which means we wipe old data
756 break;
757 }
758 }
759 case 20:
760 if (!updateFolderItemsRank(db, true)) {
761 break;
762 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800763 case 21:
764 // Recreate workspace table with screen id a primary key
765 if (!recreateWorkspaceTable(db)) {
766 break;
767 }
768 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700769 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
770 // Old version remains, which means we wipe old data
771 break;
772 }
773 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700774 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700775 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700776 case 24:
777 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700778 case 25:
779 convertShortcutsToLauncherActivities(db);
780 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800781 // DB Upgraded successfully
782 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400783 }
784 }
785
Sunny Goyala2cc6242015-01-14 14:23:02 -0800786 // DB was not upgraded
787 Log.w(TAG, "Destroying all old data.");
788 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800789 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800790
Adam Cohen9b1d0622014-05-21 19:01:57 -0700791 @Override
792 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
793 // This shouldn't happen -- throw our hands up in the air and start over.
794 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
795 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700796 createEmptyDB(db);
797 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700798
Sunny Goyal42de82f2014-09-26 22:09:29 -0700799 /**
800 * Clears all the data for a fresh start.
801 */
802 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700803 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
804 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
805 onCreate(db);
806 }
807
Sunny Goyald2f38192015-02-25 10:46:34 -0800808 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700809 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
810 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
811 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700812 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700813 db.beginTransaction();
814 Cursor c = null;
815 SQLiteStatement updateStmt = null;
816
817 try {
818 // Only consider the primary user as other users can't have a shortcut.
819 long userSerial = UserManagerCompat.getInstance(mContext)
820 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
821 c = db.query(TABLE_FAVORITES, new String[] {
822 Favorites._ID,
823 Favorites.INTENT,
824 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
825 null, null, null, null);
826
827 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
828 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
829
830 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
831 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
832
833 while (c.moveToNext()) {
834 String intentDescription = c.getString(intentIndex);
835 Intent intent;
836 try {
837 intent = Intent.parseUri(intentDescription, 0);
838 } catch (URISyntaxException e) {
839 Log.e(TAG, "Unable to parse intent", e);
840 continue;
841 }
842
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700843 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700844 continue;
845 }
846
847 long id = c.getLong(idIndex);
848 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700849 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700850 }
851 db.setTransactionSuccessful();
852 } catch (SQLException ex) {
853 Log.w(TAG, "Error deduping shortcuts", ex);
854 } finally {
855 db.endTransaction();
856 if (c != null) {
857 c.close();
858 }
859 if (updateStmt != null) {
860 updateStmt.close();
861 }
862 }
863 }
864
865 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800866 * Recreates workspace table and migrates data to the new table.
867 */
868 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
869 db.beginTransaction();
870 try {
871 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
872 new String[] {LauncherSettings.WorkspaceScreens._ID},
873 null, null, null, null,
874 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
875 ArrayList<Long> sortedIDs = new ArrayList<Long>();
876 long maxId = 0;
877 try {
878 while (c.moveToNext()) {
879 Long id = c.getLong(0);
880 if (!sortedIDs.contains(id)) {
881 sortedIDs.add(id);
882 maxId = Math.max(maxId, id);
883 }
884 }
885 } finally {
886 c.close();
887 }
888
889 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700890 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800891
892 // Add all screen ids back
893 int total = sortedIDs.size();
894 for (int i = 0; i < total; i++) {
895 ContentValues values = new ContentValues();
896 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
897 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
898 addModifiedTime(values);
899 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
900 }
901 db.setTransactionSuccessful();
902 mMaxScreenId = maxId;
903 } catch (SQLException ex) {
904 // Old version remains, which means we wipe old data
905 Log.e(TAG, ex.getMessage(), ex);
906 return false;
907 } finally {
908 db.endTransaction();
909 }
910 return true;
911 }
912
Adam Cohen091440a2015-03-18 14:16:05 -0700913 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800914 db.beginTransaction();
915 try {
916 if (addRankColumn) {
917 // Insert new column for holding rank
918 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
919 }
920
921 // Get a map for folder ID to folder width
922 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
923 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
924 + " GROUP BY container;",
925 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
926
927 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800928 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
929 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800930 new Object[] {c.getLong(1) + 1, c.getLong(0)});
931 }
932
933 c.close();
934 db.setTransactionSuccessful();
935 } catch (SQLException ex) {
936 // Old version remains, which means we wipe old data
937 Log.e(TAG, ex.getMessage(), ex);
938 return false;
939 } finally {
940 db.endTransaction();
941 }
942 return true;
943 }
944
Kenny Guyed131872014-04-30 03:02:21 +0100945 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700946 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
947 // Default to the serial number of this user, for older
948 // shortcuts.
949 long userSerialNumber = userManager.getSerialNumberForUser(
950 UserHandleCompat.myUserHandle());
951 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
952 }
953
954 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100955 db.beginTransaction();
956 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700957 db.execSQL("ALTER TABLE favorites ADD COLUMN "
958 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100959 db.setTransactionSuccessful();
960 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100961 Log.e(TAG, ex.getMessage(), ex);
962 return false;
963 } finally {
964 db.endTransaction();
965 }
966 return true;
967 }
968
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700969 // Generates a new ID to use for an object in your database. This method should be only
970 // called from the main UI thread. As an exception, we do call it when we call the
971 // constructor from the worker thread; however, this doesn't extend until after the
972 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
973 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700974 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700975 public long generateNewItemId() {
976 if (mMaxItemId < 0) {
977 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700978 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700979 mMaxItemId += 1;
980 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700981 }
982
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700983 @Override
984 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
985 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
986 }
987
Chris Wren5dee7af2013-12-20 17:22:11 -0500988 public void checkId(String table, ContentValues values) {
989 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
990 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
991 mMaxScreenId = Math.max(id, mMaxScreenId);
992 } else {
993 mMaxItemId = Math.max(id, mMaxItemId);
994 }
995 }
996
Adam Cohendcd297f2013-06-18 13:13:40 -0700997 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800998 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700999 }
1000
1001 // Generates a new ID to use for an workspace screen in your database. This method
1002 // should be only called from the main UI thread. As an exception, we do call it when we
1003 // call the constructor from the worker thread; however, this doesn't extend until after the
1004 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1005 // after that point
1006 public long generateNewScreenId() {
1007 if (mMaxScreenId < 0) {
1008 throw new RuntimeException("Error: max screen id was not initialized");
1009 }
1010 mMaxScreenId += 1;
1011 return mMaxScreenId;
1012 }
1013
Adam Cohendcd297f2013-06-18 13:13:40 -07001014 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001015 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001016 }
1017
Adam Cohen091440a2015-03-18 14:16:05 -07001018 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001019 // 1. Ensure that externally added items have a valid item id
1020 long id = generateNewItemId();
1021 values.put(LauncherSettings.Favorites._ID, id);
1022
1023 // 2. In the case of an app widget, and if no app widget id is specified, we
1024 // attempt allocate and bind the widget.
1025 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1026 if (itemType != null &&
1027 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1028 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1029
1030 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1031 ComponentName cn = ComponentName.unflattenFromString(
1032 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1033
1034 if (cn != null) {
1035 try {
1036 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001037 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001038 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001039 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001040 }
1041 } catch (RuntimeException e) {
1042 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001043 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001044 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001045 } else {
1046 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001047 }
1048 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001049
1050 // Add screen id if not present
1051 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1052 if (!addScreenIdIfNecessary(screenId)) {
1053 return false;
1054 }
Adam Cohena043fa82014-07-23 14:49:38 -07001055 return true;
1056 }
1057
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001058 // Returns true of screen id exists, or if successfully added
1059 private boolean addScreenIdIfNecessary(long screenId) {
1060 if (!hasScreenId(screenId)) {
1061 int rank = getMaxScreenRank() + 1;
1062
1063 ContentValues v = new ContentValues();
1064 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1065 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1066 if (dbInsertAndCheck(this, getWritableDatabase(),
1067 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1068 return false;
1069 }
1070 }
1071 return true;
1072 }
1073
1074 private boolean hasScreenId(long screenId) {
1075 SQLiteDatabase db = getWritableDatabase();
1076 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1077 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1078 if (c != null) {
1079 int count = c.getCount();
1080 c.close();
1081 return count > 0;
1082 } else {
1083 return false;
1084 }
1085 }
1086
1087 private int getMaxScreenRank() {
1088 SQLiteDatabase db = getWritableDatabase();
1089 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1090 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1091
1092 // get the result
1093 final int maxRankIndex = 0;
1094 int rank = -1;
1095 if (c != null && c.moveToNext()) {
1096 rank = c.getInt(maxRankIndex);
1097 }
1098 if (c != null) {
1099 c.close();
1100 }
1101
1102 return rank;
1103 }
1104
Adam Cohen091440a2015-03-18 14:16:05 -07001105 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001106 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001107 // TODO: Use multiple loaders with fall-back and transaction.
1108 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001109
1110 // Add the screens specified by the items above
1111 Collections.sort(screenIds);
1112 int rank = 0;
1113 ContentValues values = new ContentValues();
1114 for (Long id : screenIds) {
1115 values.clear();
1116 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1117 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1118 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1119 throw new RuntimeException("Failed initialize screen table"
1120 + "from default layout");
1121 }
1122 rank++;
1123 }
1124
1125 // Ensure that the max ids are initialized
1126 mMaxItemId = initializeMaxItemId(db);
1127 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001128
Adam Cohen71483f42014-05-15 14:04:01 -07001129 return count;
1130 }
1131
Adam Cohen091440a2015-03-18 14:16:05 -07001132 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001133 final ContentResolver resolver = mContext.getContentResolver();
1134 Cursor c = null;
1135 int count = 0;
1136 int curScreen = 0;
1137
1138 try {
1139 c = resolver.query(uri, null, null, null, "title ASC");
1140 } catch (Exception e) {
1141 // Ignore
1142 }
1143
Dan Sandlerd5024042014-01-09 15:01:33 -05001144 // We already have a favorites database in the old provider
1145 if (c != null) {
1146 try {
1147 if (c.getCount() > 0) {
1148 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1149 final int intentIndex
1150 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1151 final int titleIndex
1152 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1153 final int iconTypeIndex
1154 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1155 final int iconIndex
1156 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1157 final int iconPackageIndex
1158 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1159 final int iconResourceIndex
1160 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1161 final int containerIndex
1162 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1163 final int itemTypeIndex
1164 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1165 final int screenIndex
1166 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1167 final int cellXIndex
1168 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1169 final int cellYIndex
1170 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001171 final int profileIndex
1172 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001173
1174 int i = 0;
1175 int curX = 0;
1176 int curY = 0;
1177
1178 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001179 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1180 final int width = (int) profile.numColumns;
1181 final int height = (int) profile.numRows;
1182 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001183
1184 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1185
Adam Cohen72960972014-01-15 18:13:55 -08001186 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1187 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001188 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001189
1190 while (c.moveToNext()) {
1191 final int itemType = c.getInt(itemTypeIndex);
1192 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1193 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1194 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1195 continue;
1196 }
1197
1198 final int cellX = c.getInt(cellXIndex);
1199 final int cellY = c.getInt(cellYIndex);
1200 final int screen = c.getInt(screenIndex);
1201 int container = c.getInt(containerIndex);
1202 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001203
1204 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1205 UserHandleCompat userHandle;
1206 final long userSerialNumber;
1207 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1208 userSerialNumber = c.getInt(profileIndex);
1209 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1210 } else {
1211 // Default to the serial number of this user, for older
1212 // shortcuts.
1213 userHandle = UserHandleCompat.myUserHandle();
1214 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1215 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001216
1217 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001218 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001219 continue;
1220 }
1221
Dan Sandlerd5024042014-01-09 15:01:33 -05001222 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001223
1224 final Intent intent;
1225 final ComponentName cn;
1226 try {
1227 intent = Intent.parseUri(intentStr, 0);
1228 } catch (URISyntaxException e) {
1229 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001230 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001231 continue;
1232 }
1233
1234 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001235 if (TextUtils.isEmpty(intentStr)) {
1236 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001237 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001238 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001239 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001240 !LauncherModel.isValidPackageActivity(mContext, cn,
1241 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001242 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001243 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001244 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001245 } else if (container ==
1246 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1247 // Dedupe icons directly on the workspace
1248
Adam Cohen556f6132014-01-15 15:18:08 -08001249 // Canonicalize
1250 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001251 // does not, so we clear that out to keep them the same.
1252 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001253 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001254 int flags = intent.getFlags();
1255 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001256 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001257 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001258 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001259 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001260 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001261 } else {
1262 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001263 }
1264 }
1265 }
1266
1267 ContentValues values = new ContentValues(c.getColumnCount());
1268 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1269 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1270 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1271 values.put(LauncherSettings.Favorites.ICON_TYPE,
1272 c.getInt(iconTypeIndex));
1273 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1274 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1275 c.getString(iconPackageIndex));
1276 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1277 c.getString(iconResourceIndex));
1278 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1279 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001280 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001281
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001282 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1283 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001284 }
1285
1286 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1287 // In a folder or in the hotseat, preserve position
1288 values.put(LauncherSettings.Favorites.SCREEN, screen);
1289 values.put(LauncherSettings.Favorites.CELLX, cellX);
1290 values.put(LauncherSettings.Favorites.CELLY, cellY);
1291 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001292 // For items contained directly on one of the workspace screen,
1293 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001294 }
1295
1296 values.put(LauncherSettings.Favorites.CONTAINER, container);
1297
Adam Cohen72960972014-01-15 18:13:55 -08001298 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1299 shortcuts.add(values);
1300 } else {
1301 folders.add(values);
1302 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001303 }
1304
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001305 // Now that we have all the hotseat icons, let's go through them left-right
1306 // and assign valid locations for them in the new hotseat
1307 final int N = hotseat.size();
1308 for (int idx=0; idx<N; idx++) {
1309 int hotseatX = hotseat.keyAt(idx);
1310 ContentValues values = hotseat.valueAt(idx);
1311
Adam Cohen2e6da152015-05-06 11:42:25 -07001312 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001313 // let's drop this in the next available hole in the hotseat
1314 while (++hotseatX < hotseatWidth) {
1315 if (hotseat.get(hotseatX) == null) {
1316 // found a spot! move it here
1317 values.put(LauncherSettings.Favorites.SCREEN,
1318 hotseatX);
1319 break;
1320 }
1321 }
1322 }
1323 if (hotseatX >= hotseatWidth) {
1324 // no room for you in the hotseat? it's off to the desktop with you
1325 values.put(LauncherSettings.Favorites.CONTAINER,
1326 Favorites.CONTAINER_DESKTOP);
1327 }
1328 }
1329
Adam Cohen72960972014-01-15 18:13:55 -08001330 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1331 // Folders first
1332 allItems.addAll(folders);
1333 // Then shortcuts
1334 allItems.addAll(shortcuts);
1335
1336 // Layout all the folders
1337 for (ContentValues values: allItems) {
1338 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1339 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1340 // Hotseat items and folder items have already had their
1341 // location information set. Nothing to be done here.
1342 continue;
1343 }
1344 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1345 values.put(LauncherSettings.Favorites.CELLX, curX);
1346 values.put(LauncherSettings.Favorites.CELLY, curY);
1347 curX = (curX + 1) % width;
1348 if (curX == 0) {
1349 curY = (curY + 1);
1350 }
1351 // Leave the last row of icons blank on every screen
1352 if (curY == height - 1) {
1353 curScreen = (int) generateNewScreenId();
1354 curY = 0;
1355 }
1356 }
1357
1358 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001359 db.beginTransaction();
1360 try {
Adam Cohen72960972014-01-15 18:13:55 -08001361 for (ContentValues row: allItems) {
1362 if (row == null) continue;
1363 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001364 < 0) {
1365 return;
1366 } else {
1367 count++;
1368 }
1369 }
1370 db.setTransactionSuccessful();
1371 } finally {
1372 db.endTransaction();
1373 }
1374 }
1375
1376 db.beginTransaction();
1377 try {
1378 for (i=0; i<=curScreen; i++) {
1379 final ContentValues values = new ContentValues();
1380 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1381 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1382 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1383 < 0) {
1384 return;
1385 }
1386 }
1387 db.setTransactionSuccessful();
1388 } finally {
1389 db.endTransaction();
1390 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001391
1392 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001393 }
1394 } finally {
1395 c.close();
1396 }
1397 }
1398
Sunny Goyala1365452015-10-01 15:46:24 -07001399 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1400 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001401
1402 // ensure that new screens are created to hold these icons
1403 setFlagJustLoadedOldDb();
1404
1405 // Update max IDs; very important since we just grabbed IDs from another database
1406 mMaxItemId = initializeMaxItemId(db);
1407 mMaxScreenId = initializeMaxScreenId(db);
1408 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1409 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001410 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001411
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001412 /**
1413 * @return the max _id in the provided table.
1414 */
Adam Cohen091440a2015-03-18 14:16:05 -07001415 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001416 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1417 // get the result
1418 long id = -1;
1419 if (c != null && c.moveToNext()) {
1420 id = c.getLong(0);
1421 }
1422 if (c != null) {
1423 c.close();
1424 }
1425
1426 if (id == -1) {
1427 throw new RuntimeException("Error: could not query max id in " + table);
1428 }
1429
1430 return id;
1431 }
1432
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001433 static class SqlArguments {
1434 public final String table;
1435 public final String where;
1436 public final String[] args;
1437
1438 SqlArguments(Uri url, String where, String[] args) {
1439 if (url.getPathSegments().size() == 1) {
1440 this.table = url.getPathSegments().get(0);
1441 this.where = where;
1442 this.args = args;
1443 } else if (url.getPathSegments().size() != 2) {
1444 throw new IllegalArgumentException("Invalid URI: " + url);
1445 } else if (!TextUtils.isEmpty(where)) {
1446 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1447 } else {
1448 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001449 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001450 this.args = null;
1451 }
1452 }
1453
1454 SqlArguments(Uri url) {
1455 if (url.getPathSegments().size() == 1) {
1456 table = url.getPathSegments().get(0);
1457 where = null;
1458 args = null;
1459 } else {
1460 throw new IllegalArgumentException("Invalid URI: " + url);
1461 }
1462 }
1463 }
Adam Cohen72960972014-01-15 18:13:55 -08001464}