blob: 3fc0b948cdb218e2540fe2be42d5e71eb73e4254 [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 Goyal316490e2015-06-02 09:38:28 -070080 @Thunk 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 Goyald3849d12015-10-29 10:28:32 -0700107 private synchronized void createDbIfNotExists() {
108 if (mOpenHelper == null) {
109 mOpenHelper = new DatabaseHelper(getContext(), this);
110 }
111 }
112
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113 @Override
114 public Cursor query(Uri uri, String[] projection, String selection,
115 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700116 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800117
118 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
119 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
120 qb.setTables(args.table);
121
Romain Guy73b979d2009-06-09 12:57:21 -0700122 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
124 result.setNotificationUri(getContext().getContentResolver(), uri);
125
126 return result;
127 }
128
Adam Cohen091440a2015-03-18 14:16:05 -0700129 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700130 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500131 if (values == null) {
132 throw new RuntimeException("Error: attempting to insert null values");
133 }
Adam Cohen71483f42014-05-15 14:04:01 -0700134 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 throw new RuntimeException("Error: attempting to add item without specifying an id");
136 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500137 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 return db.insert(table, nullColumnHack, values);
139 }
140
Sunny Goyald1064182015-08-13 12:08:30 -0700141 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700142 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700143 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
144 if (app != null) {
145 app.reloadWorkspace();
146 }
147 }
148 }
149
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150 @Override
151 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700152 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 SqlArguments args = new SqlArguments(uri);
154
Sunny Goyald1064182015-08-13 12:08:30 -0700155 // In very limited cases, we support system|signature permission apps to modify the db.
156 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700157 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
158 return null;
159 }
160 }
161
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800162 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400163 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800165 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166
167 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700168 notifyListeners();
169
Sunny Goyalc74e4192015-09-08 14:01:03 -0700170 if (Utilities.ATLEAST_MARSHMALLOW) {
171 reloadLauncherIfExternal();
172 } else {
173 // Deprecated behavior to support legacy devices which rely on provider callbacks.
174 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
175 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
176 app.reloadWorkspace();
177 }
178
179 String notify = uri.getQueryParameter("notify");
180 if (notify == null || "true".equals(notify)) {
181 getContext().getContentResolver().notifyChange(uri, null);
182 }
183 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 return uri;
185 }
186
187 @Override
188 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700189 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190 SqlArguments args = new SqlArguments(uri);
191
192 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
193 db.beginTransaction();
194 try {
195 int numValues = values.length;
196 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400197 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700198 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
199 return 0;
200 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 }
202 db.setTransactionSuccessful();
203 } finally {
204 db.endTransaction();
205 }
206
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700207 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700208 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 return values.length;
210 }
211
212 @Override
Yura085c8532014-02-11 15:15:29 +0000213 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
214 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700215 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000216 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
217 db.beginTransaction();
218 try {
219 ContentProviderResult[] result = super.applyBatch(operations);
220 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700221 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000222 return result;
223 } finally {
224 db.endTransaction();
225 }
226 }
227
228 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700230 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
232
233 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
234 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700235 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236
Sunny Goyald1064182015-08-13 12:08:30 -0700237 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 return count;
239 }
240
241 @Override
242 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700243 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800244 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
245
Chris Wren1ada10d2013-09-13 18:01:38 -0400246 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800247 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
248 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700249 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250
Sunny Goyald1064182015-08-13 12:08:30 -0700251 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800252 return count;
253 }
254
Sunny Goyal7779d622015-06-11 16:18:39 -0700255 @Override
256 public Bundle call(String method, String arg, Bundle extras) {
257 if (Binder.getCallingUid() != Process.myUid()) {
258 return null;
259 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700260 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700261
262 switch (method) {
263 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
264 Bundle result = new Bundle();
265 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700266 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
267 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700268 return result;
269 }
270 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
271 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700272 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700273 synchronized (LISTENER_LOCK) {
274 if (mListener != null) {
275 mListener.onSettingsChanged(arg, value);
276 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700277 }
278 Bundle result = new Bundle();
279 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
280 return result;
281 }
Sunny Goyald2497482015-09-22 18:24:19 -0700282 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
283 clearFlagEmptyDbCreated();
284 return null;
285 }
286 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
287 Bundle result = new Bundle();
288 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
289 return result;
290 }
291 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
292 Bundle result = new Bundle();
293 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
294 return result;
295 }
296 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
297 Bundle result = new Bundle();
298 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
299 return result;
300 }
301 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
302 createEmptyDB();
303 return null;
304 }
305 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
306 loadDefaultFavoritesIfNecessary();
307 return null;
308 }
309 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
310 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
311 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
312 return null;
313 }
314 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
315 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
316 return null;
317 }
318 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
319 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
320 return null;
321 }
322 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800323 // Are you sure? (y/n)
324 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700325 return null;
326 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700327 }
328 return null;
329 }
330
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700331 /**
332 * Deletes any empty folder from the DB.
333 * @return Ids of deleted folders.
334 */
Sunny Goyald2497482015-09-22 18:24:19 -0700335 private ArrayList<Long> deleteEmptyFolders() {
336 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700337 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
338 db.beginTransaction();
339 try {
340 // Select folders whose id do not match any container value.
341 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
342 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
343 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
344 LauncherSettings.Favorites.CONTAINER + " FROM "
345 + TABLE_FAVORITES + ")";
346 Cursor c = db.query(TABLE_FAVORITES,
347 new String[] {LauncherSettings.Favorites._ID},
348 selection, null, null, null, null);
349 while (c.moveToNext()) {
350 folderIds.add(c.getLong(0));
351 }
352 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700353 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700354 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
355 LauncherSettings.Favorites._ID, folderIds), null);
356 }
357 db.setTransactionSuccessful();
358 } catch (SQLException ex) {
359 Log.e(TAG, ex.getMessage(), ex);
360 folderIds.clear();
361 } finally {
362 db.endTransaction();
363 }
364 return folderIds;
365 }
366
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700367 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400368 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400369 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700370 synchronized (LISTENER_LOCK) {
371 if (mListener != null) {
372 mListener.onLauncherProviderChange();
373 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700374 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400375 }
376
Adam Cohen091440a2015-03-18 14:16:05 -0700377 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400378 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800379 }
380
Brian Muramatsu5524b492012-10-02 16:55:54 -0700381 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700382 * Clears all the data for a fresh start.
383 */
Sunny Goyald2497482015-09-22 18:24:19 -0700384 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700385 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
386 }
387
Sunny Goyald2497482015-09-22 18:24:19 -0700388 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700389 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700390 }
391
Sunny Goyal42de82f2014-09-26 22:09:29 -0700392 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700393 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700394 * 1) From the app restrictions
395 * 2) From a package provided by play store
396 * 3) From a partner configuration APK, already in the system image
397 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700398 */
Sunny Goyald2497482015-09-22 18:24:19 -0700399 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700400 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700401
Winson Chungc763c4e2013-07-19 13:49:06 -0700402 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500403 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200404
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700405 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
406 if (loader == null) {
407 loader = AutoInstallsLayout.get(getContext(),
408 mOpenHelper.mAppWidgetHost, mOpenHelper);
409 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700410 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700411 final Partner partner = Partner.get(getContext().getPackageManager());
412 if (partner != null && partner.hasDefaultLayout()) {
413 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700414 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700415 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700416 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700417 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
418 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700419 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700420 }
421 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700422
Sunny Goyal9d219682014-10-23 14:21:02 -0700423 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700424 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700425 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700426 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800427
428 // There might be some partially restored DB items, due to buggy restore logic in
429 // previous versions of launcher.
430 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700431 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700432 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
433 && usingExternallyProvidedLayout) {
434 // Unable to load external layout. Cleanup and load the internal layout.
435 createEmptyDB();
436 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
437 getDefaultLayoutParser());
438 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700439 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700440 }
441 }
442
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700443 /**
444 * Creates workspace loader from an XML resource listed in the app restrictions.
445 *
446 * @return the loader if the restrictions are set and the resource exists; null otherwise.
447 */
448 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
449 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
450 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700451 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700452 return null;
453 }
454
455 Context ctx = getContext();
456 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
457 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700458 if (bundle == null) {
459 return null;
460 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700461
Sunny Goyal35ca8732015-04-06 10:45:31 -0700462 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700463 if (packageName != null) {
464 try {
465 Resources targetResources = ctx.getPackageManager()
466 .getResourcesForApplication(packageName);
467 return AutoInstallsLayout.get(ctx, packageName, targetResources,
468 mOpenHelper.mAppWidgetHost, mOpenHelper);
469 } catch (NameNotFoundException e) {
470 Log.e(TAG, "Target package for restricted profile not found", e);
471 return null;
472 }
473 }
474 return null;
475 }
476
Sunny Goyal9d219682014-10-23 14:21:02 -0700477 private DefaultLayoutParser getDefaultLayoutParser() {
478 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700479 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700480 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
481 mOpenHelper, getContext().getResources(), defaultLayout);
482 }
483
Sunny Goyald3849d12015-10-29 10:28:32 -0700484 /**
485 * Send notification that we've deleted the {@link AppWidgetHost},
486 * probably as part of the initial database creation. The receiver may
487 * want to re-call {@link AppWidgetHost#startListening()} to ensure
488 * callbacks are correctly set.
489 */
490 @Thunk void notifyAppHostReset() {
491 new MainThreadExecutor().execute(new Runnable() {
492
493 @Override
494 public void run() {
495 synchronized (LISTENER_LOCK) {
496 if (mListener != null) {
497 mListener.onAppWidgetHostReset();
498 }
499 }
500 }
501 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500502 }
503
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700504 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700505 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800506 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700507 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700508 private long mMaxItemId = -1;
509 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800510
Sunny Goyald3849d12015-10-29 10:28:32 -0700511 DatabaseHelper(Context context, LauncherProvider provider) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100512 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800513 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700514 mProvider = provider;
515
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700516 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700517
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700518 // Table creation sometimes fails silently, which leads to a crash loop.
519 // This way, we will try to create a table every time after crash, so the device
520 // would eventually be able to recover.
521 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
522 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
523 // This operation is a no-op if the table already exists.
524 addFavoritesTable(getWritableDatabase(), true);
525 addWorkspacesTable(getWritableDatabase(), true);
526 }
527
Winson Chung3d503fb2011-07-13 17:25:49 -0700528 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
529 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700530 if (mMaxItemId == -1) {
531 mMaxItemId = initializeMaxItemId(getWritableDatabase());
532 }
533 if (mMaxScreenId == -1) {
534 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700535 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800536 }
537
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700538 private boolean tableExists(String tableName) {
539 Cursor c = getReadableDatabase().query(
540 true, "sqlite_master", new String[] {"tbl_name"},
541 "tbl_name = ?", new String[] {tableName},
542 null, null, null, null, null);
543 try {
544 return c.getCount() > 0;
545 } finally {
546 c.close();
547 }
548 }
549
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550 @Override
551 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800552 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700553
Adam Cohendcd297f2013-06-18 13:13:40 -0700554 mMaxItemId = 1;
555 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700556
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700557 addFavoritesTable(db, false);
558 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700560 // Database was just created, so wipe any previous widgets
561 if (mAppWidgetHost != null) {
562 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700563 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800564 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700565
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800566 // Fresh and clean launcher DB.
567 mMaxItemId = initializeMaxItemId(db);
568 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700569
570 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700571 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 }
573
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700574 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
575 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
576 long userSerialNumber = userManager.getSerialNumberForUser(
577 UserHandleCompat.myUserHandle());
578 String ifNotExists = optional ? " IF NOT EXISTS " : "";
579
580 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
581 "_id INTEGER PRIMARY KEY," +
582 "title TEXT," +
583 "intent TEXT," +
584 "container INTEGER," +
585 "screen INTEGER," +
586 "cellX INTEGER," +
587 "cellY INTEGER," +
588 "spanX INTEGER," +
589 "spanY INTEGER," +
590 "itemType INTEGER," +
591 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
592 "isShortcut INTEGER," +
593 "iconType INTEGER," +
594 "iconPackage TEXT," +
595 "iconResource TEXT," +
596 "icon BLOB," +
597 "uri TEXT," +
598 "displayMode INTEGER," +
599 "appWidgetProvider TEXT," +
600 "modified INTEGER NOT NULL DEFAULT 0," +
601 "restored INTEGER NOT NULL DEFAULT 0," +
602 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
603 "rank INTEGER NOT NULL DEFAULT 0," +
604 "options INTEGER NOT NULL DEFAULT 0" +
605 ");");
606 }
607
608 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
609 String ifNotExists = optional ? " IF NOT EXISTS " : "";
610 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800611 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400612 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
613 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700614 ");");
615 }
616
Adam Cohen119285e2014-04-02 16:59:08 -0700617 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700618 // Delete items directly on the workspace who's screen id doesn't exist
619 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
620 // AND container = -100"
621 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
622 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700623 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700624 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
625 " AND " +
626 LauncherSettings.Favorites.CONTAINER + " = " +
627 LauncherSettings.Favorites.CONTAINER_DESKTOP;
628 db.execSQL(removeOrphanedDesktopItems);
629
630 // Delete items contained in folders which no longer exist (after above statement)
631 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
632 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
633 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
634 " WHERE " +
635 LauncherSettings.Favorites.CONTAINER + " <> " +
636 LauncherSettings.Favorites.CONTAINER_DESKTOP +
637 " AND "
638 + LauncherSettings.Favorites.CONTAINER + " <> " +
639 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
640 " AND "
641 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
642 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
643 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
644 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
645 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700646 }
647
Winson Chungc763c4e2013-07-19 13:49:06 -0700648 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700649 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700650 }
651
Winson Chungc763c4e2013-07-19 13:49:06 -0700652 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700653 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700654 }
655
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800656 @Override
657 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700658 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 switch (oldVersion) {
660 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800661 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800662 case 12: {
663 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
664 // to persist workspace screens and their relative order.
665 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700666 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800667 }
668 case 13: {
669 db.beginTransaction();
670 try {
671 // Insert new column for holding widget provider name
672 db.execSQL("ALTER TABLE favorites " +
673 "ADD COLUMN appWidgetProvider TEXT;");
674 db.setTransactionSuccessful();
675 } catch (SQLException ex) {
676 Log.e(TAG, ex.getMessage(), ex);
677 // Old version remains, which means we wipe old data
678 break;
679 } finally {
680 db.endTransaction();
681 }
682 }
683 case 14: {
684 db.beginTransaction();
685 try {
686 // Insert new column for holding update timestamp
687 db.execSQL("ALTER TABLE favorites " +
688 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
689 db.execSQL("ALTER TABLE workspaceScreens " +
690 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
691 db.setTransactionSuccessful();
692 } catch (SQLException ex) {
693 Log.e(TAG, ex.getMessage(), ex);
694 // Old version remains, which means we wipe old data
695 break;
696 } finally {
697 db.endTransaction();
698 }
699 }
700 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700701 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 // Old version remains, which means we wipe old data
703 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800704 }
705 }
706 case 16: {
707 // We use the db version upgrade here to identify users who may not have seen
708 // clings yet (because they weren't available), but for whom the clings are now
709 // available (tablet users). Because one of the possible cling flows (migration)
710 // is very destructive (wipes out workspaces), we want to prevent this from showing
711 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800712 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800713 }
714 case 17: {
715 // No-op
716 }
717 case 18: {
718 // Due to a data loss bug, some users may have items associated with screen ids
719 // which no longer exist. Since this can cause other problems, and since the user
720 // will never see these items anyway, we use database upgrade as an opportunity to
721 // clean things up.
722 removeOrphanedItems(db);
723 }
724 case 19: {
725 // Add userId column
726 if (!addProfileColumn(db)) {
727 // Old version remains, which means we wipe old data
728 break;
729 }
730 }
731 case 20:
732 if (!updateFolderItemsRank(db, true)) {
733 break;
734 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800735 case 21:
736 // Recreate workspace table with screen id a primary key
737 if (!recreateWorkspaceTable(db)) {
738 break;
739 }
740 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700741 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
742 // Old version remains, which means we wipe old data
743 break;
744 }
745 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700746 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700747 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700748 case 24:
749 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700750 case 25:
751 convertShortcutsToLauncherActivities(db);
752 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 // DB Upgraded successfully
754 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400755 }
756 }
757
Sunny Goyala2cc6242015-01-14 14:23:02 -0800758 // DB was not upgraded
759 Log.w(TAG, "Destroying all old data.");
760 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800761 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800762
Adam Cohen9b1d0622014-05-21 19:01:57 -0700763 @Override
764 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
765 // This shouldn't happen -- throw our hands up in the air and start over.
766 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
767 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700768 createEmptyDB(db);
769 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700770
Sunny Goyal42de82f2014-09-26 22:09:29 -0700771 /**
772 * Clears all the data for a fresh start.
773 */
774 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700775 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
776 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
777 onCreate(db);
778 }
779
Sunny Goyald2f38192015-02-25 10:46:34 -0800780 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700781 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
782 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
783 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700784 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700785 db.beginTransaction();
786 Cursor c = null;
787 SQLiteStatement updateStmt = null;
788
789 try {
790 // Only consider the primary user as other users can't have a shortcut.
791 long userSerial = UserManagerCompat.getInstance(mContext)
792 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
793 c = db.query(TABLE_FAVORITES, new String[] {
794 Favorites._ID,
795 Favorites.INTENT,
796 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
797 null, null, null, null);
798
799 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
800 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
801
802 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
803 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
804
805 while (c.moveToNext()) {
806 String intentDescription = c.getString(intentIndex);
807 Intent intent;
808 try {
809 intent = Intent.parseUri(intentDescription, 0);
810 } catch (URISyntaxException e) {
811 Log.e(TAG, "Unable to parse intent", e);
812 continue;
813 }
814
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700815 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 continue;
817 }
818
819 long id = c.getLong(idIndex);
820 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700821 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700822 }
823 db.setTransactionSuccessful();
824 } catch (SQLException ex) {
825 Log.w(TAG, "Error deduping shortcuts", ex);
826 } finally {
827 db.endTransaction();
828 if (c != null) {
829 c.close();
830 }
831 if (updateStmt != null) {
832 updateStmt.close();
833 }
834 }
835 }
836
837 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800838 * Recreates workspace table and migrates data to the new table.
839 */
840 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
841 db.beginTransaction();
842 try {
843 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
844 new String[] {LauncherSettings.WorkspaceScreens._ID},
845 null, null, null, null,
846 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
847 ArrayList<Long> sortedIDs = new ArrayList<Long>();
848 long maxId = 0;
849 try {
850 while (c.moveToNext()) {
851 Long id = c.getLong(0);
852 if (!sortedIDs.contains(id)) {
853 sortedIDs.add(id);
854 maxId = Math.max(maxId, id);
855 }
856 }
857 } finally {
858 c.close();
859 }
860
861 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700862 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800863
864 // Add all screen ids back
865 int total = sortedIDs.size();
866 for (int i = 0; i < total; i++) {
867 ContentValues values = new ContentValues();
868 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
869 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
870 addModifiedTime(values);
871 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
872 }
873 db.setTransactionSuccessful();
874 mMaxScreenId = maxId;
875 } catch (SQLException ex) {
876 // Old version remains, which means we wipe old data
877 Log.e(TAG, ex.getMessage(), ex);
878 return false;
879 } finally {
880 db.endTransaction();
881 }
882 return true;
883 }
884
Adam Cohen091440a2015-03-18 14:16:05 -0700885 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800886 db.beginTransaction();
887 try {
888 if (addRankColumn) {
889 // Insert new column for holding rank
890 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
891 }
892
893 // Get a map for folder ID to folder width
894 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
895 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
896 + " GROUP BY container;",
897 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
898
899 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800900 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
901 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800902 new Object[] {c.getLong(1) + 1, c.getLong(0)});
903 }
904
905 c.close();
906 db.setTransactionSuccessful();
907 } catch (SQLException ex) {
908 // Old version remains, which means we wipe old data
909 Log.e(TAG, ex.getMessage(), ex);
910 return false;
911 } finally {
912 db.endTransaction();
913 }
914 return true;
915 }
916
Kenny Guyed131872014-04-30 03:02:21 +0100917 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700918 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
919 // Default to the serial number of this user, for older
920 // shortcuts.
921 long userSerialNumber = userManager.getSerialNumberForUser(
922 UserHandleCompat.myUserHandle());
923 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
924 }
925
926 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100927 db.beginTransaction();
928 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700929 db.execSQL("ALTER TABLE favorites ADD COLUMN "
930 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100931 db.setTransactionSuccessful();
932 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100933 Log.e(TAG, ex.getMessage(), ex);
934 return false;
935 } finally {
936 db.endTransaction();
937 }
938 return true;
939 }
940
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700941 // Generates a new ID to use for an object in your database. This method should be only
942 // called from the main UI thread. As an exception, we do call it when we call the
943 // constructor from the worker thread; however, this doesn't extend until after the
944 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
945 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700946 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 public long generateNewItemId() {
948 if (mMaxItemId < 0) {
949 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700950 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700951 mMaxItemId += 1;
952 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700953 }
954
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700955 @Override
956 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
957 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
958 }
959
Chris Wren5dee7af2013-12-20 17:22:11 -0500960 public void checkId(String table, ContentValues values) {
961 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
962 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
963 mMaxScreenId = Math.max(id, mMaxScreenId);
964 } else {
965 mMaxItemId = Math.max(id, mMaxItemId);
966 }
967 }
968
Adam Cohendcd297f2013-06-18 13:13:40 -0700969 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800970 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700971 }
972
973 // Generates a new ID to use for an workspace screen in your database. This method
974 // should be only called from the main UI thread. As an exception, we do call it when we
975 // call the constructor from the worker thread; however, this doesn't extend until after the
976 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
977 // after that point
978 public long generateNewScreenId() {
979 if (mMaxScreenId < 0) {
980 throw new RuntimeException("Error: max screen id was not initialized");
981 }
982 mMaxScreenId += 1;
983 return mMaxScreenId;
984 }
985
Adam Cohendcd297f2013-06-18 13:13:40 -0700986 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800987 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800988 }
989
Adam Cohen091440a2015-03-18 14:16:05 -0700990 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700991 // 1. Ensure that externally added items have a valid item id
992 long id = generateNewItemId();
993 values.put(LauncherSettings.Favorites._ID, id);
994
995 // 2. In the case of an app widget, and if no app widget id is specified, we
996 // attempt allocate and bind the widget.
997 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
998 if (itemType != null &&
999 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1000 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1001
1002 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1003 ComponentName cn = ComponentName.unflattenFromString(
1004 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1005
1006 if (cn != null) {
1007 try {
1008 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001009 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001010 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001011 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001012 }
1013 } catch (RuntimeException e) {
1014 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001015 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001016 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001017 } else {
1018 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001019 }
1020 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001021
1022 // Add screen id if not present
1023 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1024 if (!addScreenIdIfNecessary(screenId)) {
1025 return false;
1026 }
Adam Cohena043fa82014-07-23 14:49:38 -07001027 return true;
1028 }
1029
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001030 // Returns true of screen id exists, or if successfully added
1031 private boolean addScreenIdIfNecessary(long screenId) {
1032 if (!hasScreenId(screenId)) {
1033 int rank = getMaxScreenRank() + 1;
1034
1035 ContentValues v = new ContentValues();
1036 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1037 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1038 if (dbInsertAndCheck(this, getWritableDatabase(),
1039 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1040 return false;
1041 }
1042 }
1043 return true;
1044 }
1045
1046 private boolean hasScreenId(long screenId) {
1047 SQLiteDatabase db = getWritableDatabase();
1048 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1049 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1050 if (c != null) {
1051 int count = c.getCount();
1052 c.close();
1053 return count > 0;
1054 } else {
1055 return false;
1056 }
1057 }
1058
1059 private int getMaxScreenRank() {
1060 SQLiteDatabase db = getWritableDatabase();
1061 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1062 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1063
1064 // get the result
1065 final int maxRankIndex = 0;
1066 int rank = -1;
1067 if (c != null && c.moveToNext()) {
1068 rank = c.getInt(maxRankIndex);
1069 }
1070 if (c != null) {
1071 c.close();
1072 }
1073
1074 return rank;
1075 }
1076
Adam Cohen091440a2015-03-18 14:16:05 -07001077 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001078 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001079 // TODO: Use multiple loaders with fall-back and transaction.
1080 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001081
1082 // Add the screens specified by the items above
1083 Collections.sort(screenIds);
1084 int rank = 0;
1085 ContentValues values = new ContentValues();
1086 for (Long id : screenIds) {
1087 values.clear();
1088 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1089 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1090 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1091 throw new RuntimeException("Failed initialize screen table"
1092 + "from default layout");
1093 }
1094 rank++;
1095 }
1096
1097 // Ensure that the max ids are initialized
1098 mMaxItemId = initializeMaxItemId(db);
1099 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001100
Adam Cohen71483f42014-05-15 14:04:01 -07001101 return count;
1102 }
1103
Adam Cohen091440a2015-03-18 14:16:05 -07001104 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001105 final ContentResolver resolver = mContext.getContentResolver();
1106 Cursor c = null;
1107 int count = 0;
1108 int curScreen = 0;
1109
1110 try {
1111 c = resolver.query(uri, null, null, null, "title ASC");
1112 } catch (Exception e) {
1113 // Ignore
1114 }
1115
Dan Sandlerd5024042014-01-09 15:01:33 -05001116 // We already have a favorites database in the old provider
1117 if (c != null) {
1118 try {
1119 if (c.getCount() > 0) {
1120 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1121 final int intentIndex
1122 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1123 final int titleIndex
1124 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1125 final int iconTypeIndex
1126 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1127 final int iconIndex
1128 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1129 final int iconPackageIndex
1130 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1131 final int iconResourceIndex
1132 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1133 final int containerIndex
1134 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1135 final int itemTypeIndex
1136 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1137 final int screenIndex
1138 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1139 final int cellXIndex
1140 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1141 final int cellYIndex
1142 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001143 final int profileIndex
1144 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001145
1146 int i = 0;
1147 int curX = 0;
1148 int curY = 0;
1149
1150 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001151 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1152 final int width = (int) profile.numColumns;
1153 final int height = (int) profile.numRows;
1154 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001155
1156 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1157
Adam Cohen72960972014-01-15 18:13:55 -08001158 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1159 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001160 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001161
1162 while (c.moveToNext()) {
1163 final int itemType = c.getInt(itemTypeIndex);
1164 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1165 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1166 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1167 continue;
1168 }
1169
1170 final int cellX = c.getInt(cellXIndex);
1171 final int cellY = c.getInt(cellYIndex);
1172 final int screen = c.getInt(screenIndex);
1173 int container = c.getInt(containerIndex);
1174 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001175
1176 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1177 UserHandleCompat userHandle;
1178 final long userSerialNumber;
1179 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1180 userSerialNumber = c.getInt(profileIndex);
1181 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1182 } else {
1183 // Default to the serial number of this user, for older
1184 // shortcuts.
1185 userHandle = UserHandleCompat.myUserHandle();
1186 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1187 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001188
1189 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001190 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001191 continue;
1192 }
1193
Dan Sandlerd5024042014-01-09 15:01:33 -05001194 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001195
1196 final Intent intent;
1197 final ComponentName cn;
1198 try {
1199 intent = Intent.parseUri(intentStr, 0);
1200 } catch (URISyntaxException e) {
1201 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001202 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001203 continue;
1204 }
1205
1206 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001207 if (TextUtils.isEmpty(intentStr)) {
1208 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001209 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001210 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001211 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001212 !LauncherModel.isValidPackageActivity(mContext, cn,
1213 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001214 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001215 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001216 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001217 } else if (container ==
1218 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1219 // Dedupe icons directly on the workspace
1220
Adam Cohen556f6132014-01-15 15:18:08 -08001221 // Canonicalize
1222 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001223 // does not, so we clear that out to keep them the same.
1224 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001225 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001226 int flags = intent.getFlags();
1227 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001228 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001229 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001230 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001231 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001232 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001233 } else {
1234 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001235 }
1236 }
1237 }
1238
1239 ContentValues values = new ContentValues(c.getColumnCount());
1240 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1241 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1242 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1243 values.put(LauncherSettings.Favorites.ICON_TYPE,
1244 c.getInt(iconTypeIndex));
1245 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1246 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1247 c.getString(iconPackageIndex));
1248 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1249 c.getString(iconResourceIndex));
1250 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1251 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001252 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001253
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001254 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1255 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001256 }
1257
1258 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1259 // In a folder or in the hotseat, preserve position
1260 values.put(LauncherSettings.Favorites.SCREEN, screen);
1261 values.put(LauncherSettings.Favorites.CELLX, cellX);
1262 values.put(LauncherSettings.Favorites.CELLY, cellY);
1263 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001264 // For items contained directly on one of the workspace screen,
1265 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001266 }
1267
1268 values.put(LauncherSettings.Favorites.CONTAINER, container);
1269
Adam Cohen72960972014-01-15 18:13:55 -08001270 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1271 shortcuts.add(values);
1272 } else {
1273 folders.add(values);
1274 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001275 }
1276
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001277 // Now that we have all the hotseat icons, let's go through them left-right
1278 // and assign valid locations for them in the new hotseat
1279 final int N = hotseat.size();
1280 for (int idx=0; idx<N; idx++) {
1281 int hotseatX = hotseat.keyAt(idx);
1282 ContentValues values = hotseat.valueAt(idx);
1283
Adam Cohen2e6da152015-05-06 11:42:25 -07001284 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001285 // let's drop this in the next available hole in the hotseat
1286 while (++hotseatX < hotseatWidth) {
1287 if (hotseat.get(hotseatX) == null) {
1288 // found a spot! move it here
1289 values.put(LauncherSettings.Favorites.SCREEN,
1290 hotseatX);
1291 break;
1292 }
1293 }
1294 }
1295 if (hotseatX >= hotseatWidth) {
1296 // no room for you in the hotseat? it's off to the desktop with you
1297 values.put(LauncherSettings.Favorites.CONTAINER,
1298 Favorites.CONTAINER_DESKTOP);
1299 }
1300 }
1301
Adam Cohen72960972014-01-15 18:13:55 -08001302 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1303 // Folders first
1304 allItems.addAll(folders);
1305 // Then shortcuts
1306 allItems.addAll(shortcuts);
1307
1308 // Layout all the folders
1309 for (ContentValues values: allItems) {
1310 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1311 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1312 // Hotseat items and folder items have already had their
1313 // location information set. Nothing to be done here.
1314 continue;
1315 }
1316 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1317 values.put(LauncherSettings.Favorites.CELLX, curX);
1318 values.put(LauncherSettings.Favorites.CELLY, curY);
1319 curX = (curX + 1) % width;
1320 if (curX == 0) {
1321 curY = (curY + 1);
1322 }
1323 // Leave the last row of icons blank on every screen
1324 if (curY == height - 1) {
1325 curScreen = (int) generateNewScreenId();
1326 curY = 0;
1327 }
1328 }
1329
1330 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001331 db.beginTransaction();
1332 try {
Adam Cohen72960972014-01-15 18:13:55 -08001333 for (ContentValues row: allItems) {
1334 if (row == null) continue;
1335 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001336 < 0) {
1337 return;
1338 } else {
1339 count++;
1340 }
1341 }
1342 db.setTransactionSuccessful();
1343 } finally {
1344 db.endTransaction();
1345 }
1346 }
1347
1348 db.beginTransaction();
1349 try {
1350 for (i=0; i<=curScreen; i++) {
1351 final ContentValues values = new ContentValues();
1352 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1353 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1354 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1355 < 0) {
1356 return;
1357 }
1358 }
1359 db.setTransactionSuccessful();
1360 } finally {
1361 db.endTransaction();
1362 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001363
1364 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001365 }
1366 } finally {
1367 c.close();
1368 }
1369 }
1370
Sunny Goyala1365452015-10-01 15:46:24 -07001371 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1372 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001373
1374 // ensure that new screens are created to hold these icons
1375 setFlagJustLoadedOldDb();
1376
1377 // Update max IDs; very important since we just grabbed IDs from another database
1378 mMaxItemId = initializeMaxItemId(db);
1379 mMaxScreenId = initializeMaxScreenId(db);
1380 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1381 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001382 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001383
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001384 /**
1385 * @return the max _id in the provided table.
1386 */
Adam Cohen091440a2015-03-18 14:16:05 -07001387 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001388 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1389 // get the result
1390 long id = -1;
1391 if (c != null && c.moveToNext()) {
1392 id = c.getLong(0);
1393 }
1394 if (c != null) {
1395 c.close();
1396 }
1397
1398 if (id == -1) {
1399 throw new RuntimeException("Error: could not query max id in " + table);
1400 }
1401
1402 return id;
1403 }
1404
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001405 static class SqlArguments {
1406 public final String table;
1407 public final String where;
1408 public final String[] args;
1409
1410 SqlArguments(Uri url, String where, String[] args) {
1411 if (url.getPathSegments().size() == 1) {
1412 this.table = url.getPathSegments().get(0);
1413 this.where = where;
1414 this.args = args;
1415 } else if (url.getPathSegments().size() != 2) {
1416 throw new IllegalArgumentException("Invalid URI: " + url);
1417 } else if (!TextUtils.isEmpty(where)) {
1418 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1419 } else {
1420 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001421 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001422 this.args = null;
1423 }
1424 }
1425
1426 SqlArguments(Uri url) {
1427 if (url.getPathSegments().size() == 1) {
1428 table = url.getPathSegments().get(0);
1429 where = null;
1430 args = null;
1431 } else {
1432 throw new IllegalArgumentException("Invalid URI: " + url);
1433 }
1434 }
1435 }
Adam Cohen72960972014-01-15 18:13:55 -08001436}