blob: 6598644a84f12f8d8f5f2e2e96fd068d8d209f60 [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;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080046import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050050import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070067 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Sunny Goyale5bb7052015-07-27 14:36:07 -070072 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070073
Sunny Goyal18b640c2015-04-17 09:24:01 -070074 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
75 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080076 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Sunny Goyal383c5072015-06-12 21:18:53 -070080 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070081 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
83 @Override
84 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040085 final Context context = getContext();
Sunny Goyal7bce5f72015-11-24 11:40:40 -080086 // The content provider exists for the entire duration of the launcher main process and
87 // is the first component to get created. Initializing application context here ensures
88 // that LauncherAppState always exists in the main process.
89 LauncherAppState.setApplicationContext(context.getApplicationContext());
Nilesh Agrawala258f812015-01-26 14:07:29 -080090 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080092 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040093 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 return true;
95 }
96
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
98 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -070099 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700100 }
101
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102 @Override
103 public String getType(Uri uri) {
104 SqlArguments args = new SqlArguments(uri, null, null);
105 if (TextUtils.isEmpty(args.where)) {
106 return "vnd.android.cursor.dir/" + args.table;
107 } else {
108 return "vnd.android.cursor.item/" + args.table;
109 }
110 }
111
112 @Override
113 public Cursor query(Uri uri, String[] projection, String selection,
114 String[] selectionArgs, String sortOrder) {
115
116 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
117 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
118 qb.setTables(args.table);
119
Romain Guy73b979d2009-06-09 12:57:21 -0700120 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
122 result.setNotificationUri(getContext().getContentResolver(), uri);
123
124 return result;
125 }
126
Adam Cohen091440a2015-03-18 14:16:05 -0700127 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700128 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500129 if (values == null) {
130 throw new RuntimeException("Error: attempting to insert null values");
131 }
Adam Cohen71483f42014-05-15 14:04:01 -0700132 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 throw new RuntimeException("Error: attempting to add item without specifying an id");
134 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500135 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700136 return db.insert(table, nullColumnHack, values);
137 }
138
Sunny Goyald1064182015-08-13 12:08:30 -0700139 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700140 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700141 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
142 if (app != null) {
143 app.reloadWorkspace();
144 }
145 }
146 }
147
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800148 @Override
149 public Uri insert(Uri uri, ContentValues initialValues) {
150 SqlArguments args = new SqlArguments(uri);
151
Sunny Goyald1064182015-08-13 12:08:30 -0700152 // In very limited cases, we support system|signature permission apps to modify the db.
153 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700154 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
155 return null;
156 }
157 }
158
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400160 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800162 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163
164 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700165 notifyListeners();
166
Sunny Goyalc74e4192015-09-08 14:01:03 -0700167 if (Utilities.ATLEAST_MARSHMALLOW) {
168 reloadLauncherIfExternal();
169 } else {
170 // Deprecated behavior to support legacy devices which rely on provider callbacks.
171 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
172 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
173 app.reloadWorkspace();
174 }
175
176 String notify = uri.getQueryParameter("notify");
177 if (notify == null || "true".equals(notify)) {
178 getContext().getContentResolver().notifyChange(uri, null);
179 }
180 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 return uri;
182 }
183
Adam Cohena043fa82014-07-23 14:49:38 -0700184
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185 @Override
186 public int bulkInsert(Uri uri, ContentValues[] values) {
187 SqlArguments args = new SqlArguments(uri);
188
189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
190 db.beginTransaction();
191 try {
192 int numValues = values.length;
193 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400194 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700195 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
196 return 0;
197 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198 }
199 db.setTransactionSuccessful();
200 } finally {
201 db.endTransaction();
202 }
203
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700204 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700205 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 return values.length;
207 }
208
209 @Override
Yura085c8532014-02-11 15:15:29 +0000210 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
211 throws OperationApplicationException {
212 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
213 db.beginTransaction();
214 try {
215 ContentProviderResult[] result = super.applyBatch(operations);
216 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700217 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000218 return result;
219 } finally {
220 db.endTransaction();
221 }
222 }
223
224 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225 public int delete(Uri uri, String selection, String[] selectionArgs) {
226 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
227
228 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
229 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700230 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231
Sunny Goyald1064182015-08-13 12:08:30 -0700232 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 return count;
234 }
235
236 @Override
237 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
238 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
239
Chris Wren1ada10d2013-09-13 18:01:38 -0400240 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
242 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700243 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800244
Sunny Goyald1064182015-08-13 12:08:30 -0700245 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 return count;
247 }
248
Sunny Goyal7779d622015-06-11 16:18:39 -0700249 @Override
250 public Bundle call(String method, String arg, Bundle extras) {
251 if (Binder.getCallingUid() != Process.myUid()) {
252 return null;
253 }
254
255 switch (method) {
256 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
257 Bundle result = new Bundle();
258 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700259 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
260 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700261 return result;
262 }
263 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
264 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700265 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyal7779d622015-06-11 16:18:39 -0700266 if (mListener != null) {
267 mListener.onSettingsChanged(arg, value);
268 }
269 Bundle result = new Bundle();
270 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
271 return result;
272 }
Sunny Goyald2497482015-09-22 18:24:19 -0700273 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
274 clearFlagEmptyDbCreated();
275 return null;
276 }
277 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
278 Bundle result = new Bundle();
279 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
280 return result;
281 }
282 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
283 Bundle result = new Bundle();
284 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
285 return result;
286 }
287 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
288 Bundle result = new Bundle();
289 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
290 return result;
291 }
292 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
293 createEmptyDB();
294 return null;
295 }
296 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
297 loadDefaultFavoritesIfNecessary();
298 return null;
299 }
300 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
301 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
302 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
303 return null;
304 }
305 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
306 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
307 return null;
308 }
309 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
310 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
311 return null;
312 }
313 case LauncherSettings.Settings.METHOD_DELETE_DB: {
314 deleteDatabase();
315 return null;
316 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700317 }
318 return null;
319 }
320
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700321 /**
322 * Deletes any empty folder from the DB.
323 * @return Ids of deleted folders.
324 */
Sunny Goyald2497482015-09-22 18:24:19 -0700325 private ArrayList<Long> deleteEmptyFolders() {
326 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700327 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
328 db.beginTransaction();
329 try {
330 // Select folders whose id do not match any container value.
331 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
332 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
333 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
334 LauncherSettings.Favorites.CONTAINER + " FROM "
335 + TABLE_FAVORITES + ")";
336 Cursor c = db.query(TABLE_FAVORITES,
337 new String[] {LauncherSettings.Favorites._ID},
338 selection, null, null, null, null);
339 while (c.moveToNext()) {
340 folderIds.add(c.getLong(0));
341 }
342 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700343 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700344 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
345 LauncherSettings.Favorites._ID, folderIds), null);
346 }
347 db.setTransactionSuccessful();
348 } catch (SQLException ex) {
349 Log.e(TAG, ex.getMessage(), ex);
350 folderIds.clear();
351 } finally {
352 db.endTransaction();
353 }
354 return folderIds;
355 }
356
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700357 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400358 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400359 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700360 if (mListener != null) {
361 mListener.onLauncherProviderChange();
362 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400363 }
364
Adam Cohen091440a2015-03-18 14:16:05 -0700365 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400366 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 }
368
Brian Muramatsu5524b492012-10-02 16:55:54 -0700369 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700370 * Clears all the data for a fresh start.
371 */
Sunny Goyald2497482015-09-22 18:24:19 -0700372 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700373 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
374 }
375
Sunny Goyald2497482015-09-22 18:24:19 -0700376 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700377 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700378 }
379
Sunny Goyal42de82f2014-09-26 22:09:29 -0700380 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700381 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700382 * 1) From the app restrictions
383 * 2) From a package provided by play store
384 * 3) From a partner configuration APK, already in the system image
385 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700386 */
Sunny Goyald2497482015-09-22 18:24:19 -0700387 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700388 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700389
Winson Chungc763c4e2013-07-19 13:49:06 -0700390 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500391 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200392
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700393 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
394 if (loader == null) {
395 loader = AutoInstallsLayout.get(getContext(),
396 mOpenHelper.mAppWidgetHost, mOpenHelper);
397 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700398 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700399 final Partner partner = Partner.get(getContext().getPackageManager());
400 if (partner != null && partner.hasDefaultLayout()) {
401 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700402 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700403 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700404 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700405 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
406 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700407 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700408 }
409 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700410
Sunny Goyal9d219682014-10-23 14:21:02 -0700411 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700412 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700413 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700414 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800415
416 // There might be some partially restored DB items, due to buggy restore logic in
417 // previous versions of launcher.
418 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700419 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700420 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
421 && usingExternallyProvidedLayout) {
422 // Unable to load external layout. Cleanup and load the internal layout.
423 createEmptyDB();
424 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
425 getDefaultLayoutParser());
426 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700427 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700428 }
429 }
430
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700431 /**
432 * Creates workspace loader from an XML resource listed in the app restrictions.
433 *
434 * @return the loader if the restrictions are set and the resource exists; null otherwise.
435 */
436 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
437 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
438 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700439 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700440 return null;
441 }
442
443 Context ctx = getContext();
444 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
445 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700446 if (bundle == null) {
447 return null;
448 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700449
Sunny Goyal35ca8732015-04-06 10:45:31 -0700450 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700451 if (packageName != null) {
452 try {
453 Resources targetResources = ctx.getPackageManager()
454 .getResourcesForApplication(packageName);
455 return AutoInstallsLayout.get(ctx, packageName, targetResources,
456 mOpenHelper.mAppWidgetHost, mOpenHelper);
457 } catch (NameNotFoundException e) {
458 Log.e(TAG, "Target package for restricted profile not found", e);
459 return null;
460 }
461 }
462 return null;
463 }
464
Sunny Goyal9d219682014-10-23 14:21:02 -0700465 private DefaultLayoutParser getDefaultLayoutParser() {
466 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700467 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700468 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
469 mOpenHelper, getContext().getResources(), defaultLayout);
470 }
471
Sunny Goyald2497482015-09-22 18:24:19 -0700472 private void deleteDatabase() {
Dan Sandlerd5024042014-01-09 15:01:33 -0500473 // Are you sure? (y/n)
474 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500475 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500476 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500477 if (dbFile.exists()) {
478 SQLiteDatabase.deleteDatabase(dbFile);
479 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500480 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700481 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500482 }
483
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700484 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800485 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700486 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700487 private long mMaxItemId = -1;
488 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800489
Winson Chung0b560dd2014-01-21 13:00:26 -0800490 private boolean mNewDbCreated = false;
491
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700492 @Thunk LauncherProviderChangeListener mListener;
493
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100495 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700497 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700498
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700499 // Table creation sometimes fails silently, which leads to a crash loop.
500 // This way, we will try to create a table every time after crash, so the device
501 // would eventually be able to recover.
502 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
503 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
504 // This operation is a no-op if the table already exists.
505 addFavoritesTable(getWritableDatabase(), true);
506 addWorkspacesTable(getWritableDatabase(), true);
507 }
508
Winson Chung3d503fb2011-07-13 17:25:49 -0700509 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
510 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700511 if (mMaxItemId == -1) {
512 mMaxItemId = initializeMaxItemId(getWritableDatabase());
513 }
514 if (mMaxScreenId == -1) {
515 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700516 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800517 }
518
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700519 private boolean tableExists(String tableName) {
520 Cursor c = getReadableDatabase().query(
521 true, "sqlite_master", new String[] {"tbl_name"},
522 "tbl_name = ?", new String[] {tableName},
523 null, null, null, null, null);
524 try {
525 return c.getCount() > 0;
526 } finally {
527 c.close();
528 }
529 }
530
Winson Chung0b560dd2014-01-21 13:00:26 -0800531 public boolean wasNewDbCreated() {
532 return mNewDbCreated;
533 }
534
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800535 @Override
536 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800537 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700538
Adam Cohendcd297f2013-06-18 13:13:40 -0700539 mMaxItemId = 1;
540 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800541 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700542
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700543 addFavoritesTable(db, false);
544 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700546 // Database was just created, so wipe any previous widgets
547 if (mAppWidgetHost != null) {
548 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700549
550 /**
551 * Send notification that we've deleted the {@link AppWidgetHost},
552 * probably as part of the initial database creation. The receiver may
553 * want to re-call {@link AppWidgetHost#startListening()} to ensure
554 * callbacks are correctly set.
555 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700556 new MainThreadExecutor().execute(new Runnable() {
557
558 @Override
559 public void run() {
560 if (mListener != null) {
561 mListener.onAppWidgetHostReset();
562 }
563 }
564 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700566
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800567 // Fresh and clean launcher DB.
568 mMaxItemId = initializeMaxItemId(db);
569 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700570
571 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700572 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 }
574
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700575 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
576 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
577 long userSerialNumber = userManager.getSerialNumberForUser(
578 UserHandleCompat.myUserHandle());
579 String ifNotExists = optional ? " IF NOT EXISTS " : "";
580
581 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
582 "_id INTEGER PRIMARY KEY," +
583 "title TEXT," +
584 "intent TEXT," +
585 "container INTEGER," +
586 "screen INTEGER," +
587 "cellX INTEGER," +
588 "cellY INTEGER," +
589 "spanX INTEGER," +
590 "spanY INTEGER," +
591 "itemType INTEGER," +
592 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
593 "isShortcut INTEGER," +
594 "iconType INTEGER," +
595 "iconPackage TEXT," +
596 "iconResource TEXT," +
597 "icon BLOB," +
598 "uri TEXT," +
599 "displayMode INTEGER," +
600 "appWidgetProvider TEXT," +
601 "modified INTEGER NOT NULL DEFAULT 0," +
602 "restored INTEGER NOT NULL DEFAULT 0," +
603 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
604 "rank INTEGER NOT NULL DEFAULT 0," +
605 "options INTEGER NOT NULL DEFAULT 0" +
606 ");");
607 }
608
609 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
610 String ifNotExists = optional ? " IF NOT EXISTS " : "";
611 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800612 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400613 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
614 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700615 ");");
616 }
617
Adam Cohen119285e2014-04-02 16:59:08 -0700618 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700619 // Delete items directly on the workspace who's screen id doesn't exist
620 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
621 // AND container = -100"
622 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
623 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700624 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700625 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
626 " AND " +
627 LauncherSettings.Favorites.CONTAINER + " = " +
628 LauncherSettings.Favorites.CONTAINER_DESKTOP;
629 db.execSQL(removeOrphanedDesktopItems);
630
631 // Delete items contained in folders which no longer exist (after above statement)
632 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
633 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
634 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
635 " WHERE " +
636 LauncherSettings.Favorites.CONTAINER + " <> " +
637 LauncherSettings.Favorites.CONTAINER_DESKTOP +
638 " AND "
639 + LauncherSettings.Favorites.CONTAINER + " <> " +
640 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
641 " AND "
642 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
643 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
644 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
645 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
646 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700647 }
648
Winson Chungc763c4e2013-07-19 13:49:06 -0700649 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700650 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700651 }
652
Winson Chungc763c4e2013-07-19 13:49:06 -0700653 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700654 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700655 }
656
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800657 @Override
658 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700659 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800660 switch (oldVersion) {
661 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800662 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800663 case 12: {
664 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
665 // to persist workspace screens and their relative order.
666 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700667 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800668 }
669 case 13: {
670 db.beginTransaction();
671 try {
672 // Insert new column for holding widget provider name
673 db.execSQL("ALTER TABLE favorites " +
674 "ADD COLUMN appWidgetProvider TEXT;");
675 db.setTransactionSuccessful();
676 } catch (SQLException ex) {
677 Log.e(TAG, ex.getMessage(), ex);
678 // Old version remains, which means we wipe old data
679 break;
680 } finally {
681 db.endTransaction();
682 }
683 }
684 case 14: {
685 db.beginTransaction();
686 try {
687 // Insert new column for holding update timestamp
688 db.execSQL("ALTER TABLE favorites " +
689 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
690 db.execSQL("ALTER TABLE workspaceScreens " +
691 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
692 db.setTransactionSuccessful();
693 } catch (SQLException ex) {
694 Log.e(TAG, ex.getMessage(), ex);
695 // Old version remains, which means we wipe old data
696 break;
697 } finally {
698 db.endTransaction();
699 }
700 }
701 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700702 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800703 // Old version remains, which means we wipe old data
704 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800705 }
706 }
707 case 16: {
708 // We use the db version upgrade here to identify users who may not have seen
709 // clings yet (because they weren't available), but for whom the clings are now
710 // available (tablet users). Because one of the possible cling flows (migration)
711 // is very destructive (wipes out workspaces), we want to prevent this from showing
712 // until clear data. We do so by marking that the clings have been shown.
713 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
714 }
715 case 17: {
716 // No-op
717 }
718 case 18: {
719 // Due to a data loss bug, some users may have items associated with screen ids
720 // which no longer exist. Since this can cause other problems, and since the user
721 // will never see these items anyway, we use database upgrade as an opportunity to
722 // clean things up.
723 removeOrphanedItems(db);
724 }
725 case 19: {
726 // Add userId column
727 if (!addProfileColumn(db)) {
728 // Old version remains, which means we wipe old data
729 break;
730 }
731 }
732 case 20:
733 if (!updateFolderItemsRank(db, true)) {
734 break;
735 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800736 case 21:
737 // Recreate workspace table with screen id a primary key
738 if (!recreateWorkspaceTable(db)) {
739 break;
740 }
741 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700742 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
743 // Old version remains, which means we wipe old data
744 break;
745 }
746 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700747 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700748 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700749 case 24:
750 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700751 case 25:
752 convertShortcutsToLauncherActivities(db);
753 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 // DB Upgraded successfully
755 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400756 }
757 }
758
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 // DB was not upgraded
760 Log.w(TAG, "Destroying all old data.");
761 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800762 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800763
Adam Cohen9b1d0622014-05-21 19:01:57 -0700764 @Override
765 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
766 // This shouldn't happen -- throw our hands up in the air and start over.
767 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
768 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700769 createEmptyDB(db);
770 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700771
Sunny Goyal42de82f2014-09-26 22:09:29 -0700772 /**
773 * Clears all the data for a fresh start.
774 */
775 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700776 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
777 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
778 onCreate(db);
779 }
780
Sunny Goyald2f38192015-02-25 10:46:34 -0800781 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700782 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
783 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
784 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700785 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700786 db.beginTransaction();
787 Cursor c = null;
788 SQLiteStatement updateStmt = null;
789
790 try {
791 // Only consider the primary user as other users can't have a shortcut.
792 long userSerial = UserManagerCompat.getInstance(mContext)
793 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
794 c = db.query(TABLE_FAVORITES, new String[] {
795 Favorites._ID,
796 Favorites.INTENT,
797 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
798 null, null, null, null);
799
800 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
801 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
802
803 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
804 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
805
806 while (c.moveToNext()) {
807 String intentDescription = c.getString(intentIndex);
808 Intent intent;
809 try {
810 intent = Intent.parseUri(intentDescription, 0);
811 } catch (URISyntaxException e) {
812 Log.e(TAG, "Unable to parse intent", e);
813 continue;
814 }
815
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700816 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700817 continue;
818 }
819
820 long id = c.getLong(idIndex);
821 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700822 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700823 }
824 db.setTransactionSuccessful();
825 } catch (SQLException ex) {
826 Log.w(TAG, "Error deduping shortcuts", ex);
827 } finally {
828 db.endTransaction();
829 if (c != null) {
830 c.close();
831 }
832 if (updateStmt != null) {
833 updateStmt.close();
834 }
835 }
836 }
837
838 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800839 * Recreates workspace table and migrates data to the new table.
840 */
841 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
842 db.beginTransaction();
843 try {
844 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
845 new String[] {LauncherSettings.WorkspaceScreens._ID},
846 null, null, null, null,
847 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
848 ArrayList<Long> sortedIDs = new ArrayList<Long>();
849 long maxId = 0;
850 try {
851 while (c.moveToNext()) {
852 Long id = c.getLong(0);
853 if (!sortedIDs.contains(id)) {
854 sortedIDs.add(id);
855 maxId = Math.max(maxId, id);
856 }
857 }
858 } finally {
859 c.close();
860 }
861
862 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700863 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800864
865 // Add all screen ids back
866 int total = sortedIDs.size();
867 for (int i = 0; i < total; i++) {
868 ContentValues values = new ContentValues();
869 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
870 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
871 addModifiedTime(values);
872 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
873 }
874 db.setTransactionSuccessful();
875 mMaxScreenId = maxId;
876 } catch (SQLException ex) {
877 // Old version remains, which means we wipe old data
878 Log.e(TAG, ex.getMessage(), ex);
879 return false;
880 } finally {
881 db.endTransaction();
882 }
883 return true;
884 }
885
Adam Cohen091440a2015-03-18 14:16:05 -0700886 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800887 db.beginTransaction();
888 try {
889 if (addRankColumn) {
890 // Insert new column for holding rank
891 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
892 }
893
894 // Get a map for folder ID to folder width
895 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
896 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
897 + " GROUP BY container;",
898 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
899
900 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800901 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
902 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800903 new Object[] {c.getLong(1) + 1, c.getLong(0)});
904 }
905
906 c.close();
907 db.setTransactionSuccessful();
908 } catch (SQLException ex) {
909 // Old version remains, which means we wipe old data
910 Log.e(TAG, ex.getMessage(), ex);
911 return false;
912 } finally {
913 db.endTransaction();
914 }
915 return true;
916 }
917
Kenny Guyed131872014-04-30 03:02:21 +0100918 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700919 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
920 // Default to the serial number of this user, for older
921 // shortcuts.
922 long userSerialNumber = userManager.getSerialNumberForUser(
923 UserHandleCompat.myUserHandle());
924 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
925 }
926
927 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100928 db.beginTransaction();
929 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700930 db.execSQL("ALTER TABLE favorites ADD COLUMN "
931 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100932 db.setTransactionSuccessful();
933 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100934 Log.e(TAG, ex.getMessage(), ex);
935 return false;
936 } finally {
937 db.endTransaction();
938 }
939 return true;
940 }
941
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700942 // Generates a new ID to use for an object in your database. This method should be only
943 // called from the main UI thread. As an exception, we do call it when we call the
944 // constructor from the worker thread; however, this doesn't extend until after the
945 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
946 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700947 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 public long generateNewItemId() {
949 if (mMaxItemId < 0) {
950 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700951 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700952 mMaxItemId += 1;
953 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700954 }
955
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700956 @Override
957 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
958 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
959 }
960
Chris Wren5dee7af2013-12-20 17:22:11 -0500961 public void checkId(String table, ContentValues values) {
962 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
963 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
964 mMaxScreenId = Math.max(id, mMaxScreenId);
965 } else {
966 mMaxItemId = Math.max(id, mMaxItemId);
967 }
968 }
969
Adam Cohendcd297f2013-06-18 13:13:40 -0700970 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800971 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700972 }
973
974 // Generates a new ID to use for an workspace screen in your database. This method
975 // should be only called from the main UI thread. As an exception, we do call it when we
976 // call the constructor from the worker thread; however, this doesn't extend until after the
977 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
978 // after that point
979 public long generateNewScreenId() {
980 if (mMaxScreenId < 0) {
981 throw new RuntimeException("Error: max screen id was not initialized");
982 }
983 mMaxScreenId += 1;
984 return mMaxScreenId;
985 }
986
Adam Cohendcd297f2013-06-18 13:13:40 -0700987 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800988 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800989 }
990
Adam Cohen091440a2015-03-18 14:16:05 -0700991 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700992 // 1. Ensure that externally added items have a valid item id
993 long id = generateNewItemId();
994 values.put(LauncherSettings.Favorites._ID, id);
995
996 // 2. In the case of an app widget, and if no app widget id is specified, we
997 // attempt allocate and bind the widget.
998 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
999 if (itemType != null &&
1000 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1001 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1002
1003 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1004 ComponentName cn = ComponentName.unflattenFromString(
1005 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1006
1007 if (cn != null) {
1008 try {
1009 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001010 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001011 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001012 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001013 }
1014 } catch (RuntimeException e) {
1015 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001016 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001017 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001018 } else {
1019 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001020 }
1021 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001022
1023 // Add screen id if not present
1024 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1025 if (!addScreenIdIfNecessary(screenId)) {
1026 return false;
1027 }
Adam Cohena043fa82014-07-23 14:49:38 -07001028 return true;
1029 }
1030
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001031 // Returns true of screen id exists, or if successfully added
1032 private boolean addScreenIdIfNecessary(long screenId) {
1033 if (!hasScreenId(screenId)) {
1034 int rank = getMaxScreenRank() + 1;
1035
1036 ContentValues v = new ContentValues();
1037 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1038 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1039 if (dbInsertAndCheck(this, getWritableDatabase(),
1040 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1041 return false;
1042 }
1043 }
1044 return true;
1045 }
1046
1047 private boolean hasScreenId(long screenId) {
1048 SQLiteDatabase db = getWritableDatabase();
1049 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1050 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1051 if (c != null) {
1052 int count = c.getCount();
1053 c.close();
1054 return count > 0;
1055 } else {
1056 return false;
1057 }
1058 }
1059
1060 private int getMaxScreenRank() {
1061 SQLiteDatabase db = getWritableDatabase();
1062 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1063 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1064
1065 // get the result
1066 final int maxRankIndex = 0;
1067 int rank = -1;
1068 if (c != null && c.moveToNext()) {
1069 rank = c.getInt(maxRankIndex);
1070 }
1071 if (c != null) {
1072 c.close();
1073 }
1074
1075 return rank;
1076 }
1077
Adam Cohen091440a2015-03-18 14:16:05 -07001078 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001079 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001080 // TODO: Use multiple loaders with fall-back and transaction.
1081 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001082
1083 // Add the screens specified by the items above
1084 Collections.sort(screenIds);
1085 int rank = 0;
1086 ContentValues values = new ContentValues();
1087 for (Long id : screenIds) {
1088 values.clear();
1089 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1090 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1091 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1092 throw new RuntimeException("Failed initialize screen table"
1093 + "from default layout");
1094 }
1095 rank++;
1096 }
1097
1098 // Ensure that the max ids are initialized
1099 mMaxItemId = initializeMaxItemId(db);
1100 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001101
Adam Cohen71483f42014-05-15 14:04:01 -07001102 return count;
1103 }
1104
Adam Cohen091440a2015-03-18 14:16:05 -07001105 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001106 final ContentResolver resolver = mContext.getContentResolver();
1107 Cursor c = null;
1108 int count = 0;
1109 int curScreen = 0;
1110
1111 try {
1112 c = resolver.query(uri, null, null, null, "title ASC");
1113 } catch (Exception e) {
1114 // Ignore
1115 }
1116
Dan Sandlerd5024042014-01-09 15:01:33 -05001117 // We already have a favorites database in the old provider
1118 if (c != null) {
1119 try {
1120 if (c.getCount() > 0) {
1121 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1122 final int intentIndex
1123 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1124 final int titleIndex
1125 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1126 final int iconTypeIndex
1127 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1128 final int iconIndex
1129 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1130 final int iconPackageIndex
1131 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1132 final int iconResourceIndex
1133 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1134 final int containerIndex
1135 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1136 final int itemTypeIndex
1137 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1138 final int screenIndex
1139 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1140 final int cellXIndex
1141 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1142 final int cellYIndex
1143 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001144 final int profileIndex
1145 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001146
1147 int i = 0;
1148 int curX = 0;
1149 int curY = 0;
1150
1151 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001152 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1153 final int width = (int) profile.numColumns;
1154 final int height = (int) profile.numRows;
1155 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001156
1157 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1158
Adam Cohen72960972014-01-15 18:13:55 -08001159 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1160 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001161 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001162
1163 while (c.moveToNext()) {
1164 final int itemType = c.getInt(itemTypeIndex);
1165 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1166 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1167 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1168 continue;
1169 }
1170
1171 final int cellX = c.getInt(cellXIndex);
1172 final int cellY = c.getInt(cellYIndex);
1173 final int screen = c.getInt(screenIndex);
1174 int container = c.getInt(containerIndex);
1175 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001176
1177 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1178 UserHandleCompat userHandle;
1179 final long userSerialNumber;
1180 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1181 userSerialNumber = c.getInt(profileIndex);
1182 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1183 } else {
1184 // Default to the serial number of this user, for older
1185 // shortcuts.
1186 userHandle = UserHandleCompat.myUserHandle();
1187 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1188 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001189
1190 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001191 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001192 continue;
1193 }
1194
Dan Sandlerd5024042014-01-09 15:01:33 -05001195 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001196
1197 final Intent intent;
1198 final ComponentName cn;
1199 try {
1200 intent = Intent.parseUri(intentStr, 0);
1201 } catch (URISyntaxException e) {
1202 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001203 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001204 continue;
1205 }
1206
1207 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001208 if (TextUtils.isEmpty(intentStr)) {
1209 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001210 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001211 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001212 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001213 !LauncherModel.isValidPackageActivity(mContext, cn,
1214 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001215 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001216 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001217 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001218 } else if (container ==
1219 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1220 // Dedupe icons directly on the workspace
1221
Adam Cohen556f6132014-01-15 15:18:08 -08001222 // Canonicalize
1223 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001224 // does not, so we clear that out to keep them the same.
1225 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001226 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001227 int flags = intent.getFlags();
1228 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001229 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001230 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001231 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001232 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001233 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001234 } else {
1235 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001236 }
1237 }
1238 }
1239
1240 ContentValues values = new ContentValues(c.getColumnCount());
1241 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1242 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1243 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1244 values.put(LauncherSettings.Favorites.ICON_TYPE,
1245 c.getInt(iconTypeIndex));
1246 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1247 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1248 c.getString(iconPackageIndex));
1249 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1250 c.getString(iconResourceIndex));
1251 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1252 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001253 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001254
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001255 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1256 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001257 }
1258
1259 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1260 // In a folder or in the hotseat, preserve position
1261 values.put(LauncherSettings.Favorites.SCREEN, screen);
1262 values.put(LauncherSettings.Favorites.CELLX, cellX);
1263 values.put(LauncherSettings.Favorites.CELLY, cellY);
1264 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001265 // For items contained directly on one of the workspace screen,
1266 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001267 }
1268
1269 values.put(LauncherSettings.Favorites.CONTAINER, container);
1270
Adam Cohen72960972014-01-15 18:13:55 -08001271 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1272 shortcuts.add(values);
1273 } else {
1274 folders.add(values);
1275 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001276 }
1277
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001278 // Now that we have all the hotseat icons, let's go through them left-right
1279 // and assign valid locations for them in the new hotseat
1280 final int N = hotseat.size();
1281 for (int idx=0; idx<N; idx++) {
1282 int hotseatX = hotseat.keyAt(idx);
1283 ContentValues values = hotseat.valueAt(idx);
1284
Adam Cohen2e6da152015-05-06 11:42:25 -07001285 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001286 // let's drop this in the next available hole in the hotseat
1287 while (++hotseatX < hotseatWidth) {
1288 if (hotseat.get(hotseatX) == null) {
1289 // found a spot! move it here
1290 values.put(LauncherSettings.Favorites.SCREEN,
1291 hotseatX);
1292 break;
1293 }
1294 }
1295 }
1296 if (hotseatX >= hotseatWidth) {
1297 // no room for you in the hotseat? it's off to the desktop with you
1298 values.put(LauncherSettings.Favorites.CONTAINER,
1299 Favorites.CONTAINER_DESKTOP);
1300 }
1301 }
1302
Adam Cohen72960972014-01-15 18:13:55 -08001303 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1304 // Folders first
1305 allItems.addAll(folders);
1306 // Then shortcuts
1307 allItems.addAll(shortcuts);
1308
1309 // Layout all the folders
1310 for (ContentValues values: allItems) {
1311 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1312 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1313 // Hotseat items and folder items have already had their
1314 // location information set. Nothing to be done here.
1315 continue;
1316 }
1317 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1318 values.put(LauncherSettings.Favorites.CELLX, curX);
1319 values.put(LauncherSettings.Favorites.CELLY, curY);
1320 curX = (curX + 1) % width;
1321 if (curX == 0) {
1322 curY = (curY + 1);
1323 }
1324 // Leave the last row of icons blank on every screen
1325 if (curY == height - 1) {
1326 curScreen = (int) generateNewScreenId();
1327 curY = 0;
1328 }
1329 }
1330
1331 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001332 db.beginTransaction();
1333 try {
Adam Cohen72960972014-01-15 18:13:55 -08001334 for (ContentValues row: allItems) {
1335 if (row == null) continue;
1336 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001337 < 0) {
1338 return;
1339 } else {
1340 count++;
1341 }
1342 }
1343 db.setTransactionSuccessful();
1344 } finally {
1345 db.endTransaction();
1346 }
1347 }
1348
1349 db.beginTransaction();
1350 try {
1351 for (i=0; i<=curScreen; i++) {
1352 final ContentValues values = new ContentValues();
1353 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1354 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1355 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1356 < 0) {
1357 return;
1358 }
1359 }
1360 db.setTransactionSuccessful();
1361 } finally {
1362 db.endTransaction();
1363 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001364
1365 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001366 }
1367 } finally {
1368 c.close();
1369 }
1370 }
1371
Sunny Goyala1365452015-10-01 15:46:24 -07001372 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1373 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001374
1375 // ensure that new screens are created to hold these icons
1376 setFlagJustLoadedOldDb();
1377
1378 // Update max IDs; very important since we just grabbed IDs from another database
1379 mMaxItemId = initializeMaxItemId(db);
1380 mMaxScreenId = initializeMaxScreenId(db);
1381 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1382 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001383 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001384
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001385 /**
1386 * @return the max _id in the provided table.
1387 */
Adam Cohen091440a2015-03-18 14:16:05 -07001388 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001389 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1390 // get the result
1391 long id = -1;
1392 if (c != null && c.moveToNext()) {
1393 id = c.getLong(0);
1394 }
1395 if (c != null) {
1396 c.close();
1397 }
1398
1399 if (id == -1) {
1400 throw new RuntimeException("Error: could not query max id in " + table);
1401 }
1402
1403 return id;
1404 }
1405
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001406 static class SqlArguments {
1407 public final String table;
1408 public final String where;
1409 public final String[] args;
1410
1411 SqlArguments(Uri url, String where, String[] args) {
1412 if (url.getPathSegments().size() == 1) {
1413 this.table = url.getPathSegments().get(0);
1414 this.where = where;
1415 this.args = args;
1416 } else if (url.getPathSegments().size() != 2) {
1417 throw new IllegalArgumentException("Invalid URI: " + url);
1418 } else if (!TextUtils.isEmpty(where)) {
1419 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1420 } else {
1421 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001422 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001423 this.args = null;
1424 }
1425 }
1426
1427 SqlArguments(Uri url) {
1428 if (url.getPathSegments().size() == 1) {
1429 table = url.getPathSegments().get(0);
1430 where = null;
1431 args = null;
1432 } else {
1433 throw new IllegalArgumentException("Invalid URI: " + url);
1434 }
1435 }
1436 }
Adam Cohen72960972014-01-15 18:13:55 -08001437}