blob: 47ceb8c6e7b377c97c581e571c24240ea69a4879 [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;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070057import com.android.launcher3.util.NoLocaleSqliteContext;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Mike Cleronb87bd162009-10-30 16:36:56 -070060import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070061import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070062import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050063import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070066 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068
Sunny Goyal5c97f512015-05-19 16:03:28 -070069 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Sunny Goyale5bb7052015-07-27 14:36:07 -070071 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070072
Sunny Goyal18b640c2015-04-17 09:24:01 -070073 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
74 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080075 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070077 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
78
Sunny Goyald3849d12015-10-29 10:28:32 -070079 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070080 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyalf076eae2016-01-11 12:25:10 -080081 protected 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 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 return true;
87 }
88
Sunny Goyald3849d12015-10-29 10:28:32 -070089 /**
90 * Sets a provider listener.
91 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070092 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070093 synchronized (LISTENER_LOCK) {
94 mListener = listener;
95 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070096 }
97
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 @Override
99 public String getType(Uri uri) {
100 SqlArguments args = new SqlArguments(uri, null, null);
101 if (TextUtils.isEmpty(args.where)) {
102 return "vnd.android.cursor.dir/" + args.table;
103 } else {
104 return "vnd.android.cursor.item/" + args.table;
105 }
106 }
107
Sunny Goyalf076eae2016-01-11 12:25:10 -0800108 /**
109 * Overridden in tests
110 */
111 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700112 if (mOpenHelper == null) {
113 mOpenHelper = new DatabaseHelper(getContext(), this);
114 }
115 }
116
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800117 @Override
118 public Cursor query(Uri uri, String[] projection, String selection,
119 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700120 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121
122 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
123 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
124 qb.setTables(args.table);
125
Romain Guy73b979d2009-06-09 12:57:21 -0700126 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
128 result.setNotificationUri(getContext().getContentResolver(), uri);
129
130 return result;
131 }
132
Adam Cohen091440a2015-03-18 14:16:05 -0700133 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500135 if (values == null) {
136 throw new RuntimeException("Error: attempting to insert null values");
137 }
Adam Cohen71483f42014-05-15 14:04:01 -0700138 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 throw new RuntimeException("Error: attempting to add item without specifying an id");
140 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500141 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700142 return db.insert(table, nullColumnHack, values);
143 }
144
Sunny Goyald1064182015-08-13 12:08:30 -0700145 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700146 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700147 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
148 if (app != null) {
149 app.reloadWorkspace();
150 }
151 }
152 }
153
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800154 @Override
155 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700156 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800157 SqlArguments args = new SqlArguments(uri);
158
Sunny Goyald1064182015-08-13 12:08:30 -0700159 // In very limited cases, we support system|signature permission apps to modify the db.
160 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700161 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
162 return null;
163 }
164 }
165
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400167 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700168 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800169 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170
171 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700172 notifyListeners();
173
Sunny Goyalc74e4192015-09-08 14:01:03 -0700174 if (Utilities.ATLEAST_MARSHMALLOW) {
175 reloadLauncherIfExternal();
176 } else {
177 // Deprecated behavior to support legacy devices which rely on provider callbacks.
178 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
179 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
180 app.reloadWorkspace();
181 }
182
183 String notify = uri.getQueryParameter("notify");
184 if (notify == null || "true".equals(notify)) {
185 getContext().getContentResolver().notifyChange(uri, null);
186 }
187 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800188 return uri;
189 }
190
191 @Override
192 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700193 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 SqlArguments args = new SqlArguments(uri);
195
196 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
197 db.beginTransaction();
198 try {
199 int numValues = values.length;
200 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400201 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
203 return 0;
204 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800205 }
206 db.setTransactionSuccessful();
207 } finally {
208 db.endTransaction();
209 }
210
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700211 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700212 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 return values.length;
214 }
215
216 @Override
Yura085c8532014-02-11 15:15:29 +0000217 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
218 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700219 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000220 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
221 db.beginTransaction();
222 try {
223 ContentProviderResult[] result = super.applyBatch(operations);
224 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700225 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000226 return result;
227 } finally {
228 db.endTransaction();
229 }
230 }
231
232 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700234 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
236
237 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
238 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700239 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240
Sunny Goyald1064182015-08-13 12:08:30 -0700241 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return count;
243 }
244
245 @Override
246 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700247 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
249
Chris Wren1ada10d2013-09-13 18:01:38 -0400250 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800251 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
252 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700253 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800254
Sunny Goyald1064182015-08-13 12:08:30 -0700255 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800256 return count;
257 }
258
Sunny Goyal7779d622015-06-11 16:18:39 -0700259 @Override
260 public Bundle call(String method, String arg, Bundle extras) {
261 if (Binder.getCallingUid() != Process.myUid()) {
262 return null;
263 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700264 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700265
266 switch (method) {
267 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
268 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800269 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
270 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
271 Utilities.isAllowRotationPrefEnabled(getContext()));
272 } else {
273 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
274 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
275 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
276 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700277 return result;
278 }
279 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
280 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700281 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700282 synchronized (LISTENER_LOCK) {
283 if (mListener != null) {
284 mListener.onSettingsChanged(arg, value);
285 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700286 }
Sunny Goyalb171e562016-01-21 16:41:54 -0800287 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
288 LauncherBackupAgentHelper.dataChanged(getContext());
289 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700290 Bundle result = new Bundle();
291 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
292 return result;
293 }
Sunny Goyald2497482015-09-22 18:24:19 -0700294 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
295 clearFlagEmptyDbCreated();
296 return null;
297 }
298 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
299 Bundle result = new Bundle();
300 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
301 return result;
302 }
303 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
304 Bundle result = new Bundle();
305 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
306 return result;
307 }
308 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
309 Bundle result = new Bundle();
310 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
311 return result;
312 }
313 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
314 createEmptyDB();
315 return null;
316 }
317 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
318 loadDefaultFavoritesIfNecessary();
319 return null;
320 }
321 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
322 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
323 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
324 return null;
325 }
326 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
327 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
328 return null;
329 }
330 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
331 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
332 return null;
333 }
334 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800335 // Are you sure? (y/n)
336 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700337 return null;
338 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700339 }
340 return null;
341 }
342
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700343 /**
344 * Deletes any empty folder from the DB.
345 * @return Ids of deleted folders.
346 */
Sunny Goyald2497482015-09-22 18:24:19 -0700347 private ArrayList<Long> deleteEmptyFolders() {
348 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700349 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
350 db.beginTransaction();
351 try {
352 // Select folders whose id do not match any container value.
353 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
354 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
355 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
356 LauncherSettings.Favorites.CONTAINER + " FROM "
357 + TABLE_FAVORITES + ")";
358 Cursor c = db.query(TABLE_FAVORITES,
359 new String[] {LauncherSettings.Favorites._ID},
360 selection, null, null, null, null);
361 while (c.moveToNext()) {
362 folderIds.add(c.getLong(0));
363 }
364 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700365 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700366 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
367 LauncherSettings.Favorites._ID, folderIds), null);
368 }
369 db.setTransactionSuccessful();
370 } catch (SQLException ex) {
371 Log.e(TAG, ex.getMessage(), ex);
372 folderIds.clear();
373 } finally {
374 db.endTransaction();
375 }
376 return folderIds;
377 }
378
Sunny Goyalf076eae2016-01-11 12:25:10 -0800379 /**
380 * Overridden in tests
381 */
382 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400383 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400384 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700385 synchronized (LISTENER_LOCK) {
386 if (mListener != null) {
387 mListener.onLauncherProviderChange();
388 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700389 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400390 }
391
Adam Cohen091440a2015-03-18 14:16:05 -0700392 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400393 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 }
395
Brian Muramatsu5524b492012-10-02 16:55:54 -0700396 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700397 * Clears all the data for a fresh start.
398 */
Sunny Goyald2497482015-09-22 18:24:19 -0700399 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700400 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
401 }
402
Sunny Goyald2497482015-09-22 18:24:19 -0700403 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700404 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700405 }
406
Sunny Goyal42de82f2014-09-26 22:09:29 -0700407 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700408 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700409 * 1) From the app restrictions
410 * 2) From a package provided by play store
411 * 3) From a partner configuration APK, already in the system image
412 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700413 */
Sunny Goyald2497482015-09-22 18:24:19 -0700414 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700415 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700416
Winson Chungc763c4e2013-07-19 13:49:06 -0700417 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500418 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200419
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700420 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
421 if (loader == null) {
422 loader = AutoInstallsLayout.get(getContext(),
423 mOpenHelper.mAppWidgetHost, mOpenHelper);
424 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700425 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700426 final Partner partner = Partner.get(getContext().getPackageManager());
427 if (partner != null && partner.hasDefaultLayout()) {
428 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700429 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700430 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700431 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700432 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
433 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700434 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700435 }
436 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700437
Sunny Goyal9d219682014-10-23 14:21:02 -0700438 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700439 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700440 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700441 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800442
443 // There might be some partially restored DB items, due to buggy restore logic in
444 // previous versions of launcher.
445 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700446 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700447 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
448 && usingExternallyProvidedLayout) {
449 // Unable to load external layout. Cleanup and load the internal layout.
450 createEmptyDB();
451 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
452 getDefaultLayoutParser());
453 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700454 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700455 }
456 }
457
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700458 /**
459 * Creates workspace loader from an XML resource listed in the app restrictions.
460 *
461 * @return the loader if the restrictions are set and the resource exists; null otherwise.
462 */
463 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
464 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
465 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700466 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700467 return null;
468 }
469
470 Context ctx = getContext();
471 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
472 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700473 if (bundle == null) {
474 return null;
475 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700476
Sunny Goyal35ca8732015-04-06 10:45:31 -0700477 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700478 if (packageName != null) {
479 try {
480 Resources targetResources = ctx.getPackageManager()
481 .getResourcesForApplication(packageName);
482 return AutoInstallsLayout.get(ctx, packageName, targetResources,
483 mOpenHelper.mAppWidgetHost, mOpenHelper);
484 } catch (NameNotFoundException e) {
485 Log.e(TAG, "Target package for restricted profile not found", e);
486 return null;
487 }
488 }
489 return null;
490 }
491
Sunny Goyal9d219682014-10-23 14:21:02 -0700492 private DefaultLayoutParser getDefaultLayoutParser() {
493 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700494 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
496 mOpenHelper, getContext().getResources(), defaultLayout);
497 }
498
Sunny Goyald3849d12015-10-29 10:28:32 -0700499 /**
500 * Send notification that we've deleted the {@link AppWidgetHost},
501 * probably as part of the initial database creation. The receiver may
502 * want to re-call {@link AppWidgetHost#startListening()} to ensure
503 * callbacks are correctly set.
504 */
505 @Thunk void notifyAppHostReset() {
506 new MainThreadExecutor().execute(new Runnable() {
507
508 @Override
509 public void run() {
510 synchronized (LISTENER_LOCK) {
511 if (mListener != null) {
512 mListener.onAppWidgetHostReset();
513 }
514 }
515 }
516 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500517 }
518
Sunny Goyalf076eae2016-01-11 12:25:10 -0800519 /**
520 * The class is subclassed in tests to create an in-memory db.
521 */
522 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800524 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700525 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700526 private long mMaxItemId = -1;
527 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800528
Sunny Goyald3849d12015-10-29 10:28:32 -0700529 DatabaseHelper(Context context, LauncherProvider provider) {
Sunny Goyalbf67f3b2016-03-15 15:30:11 -0700530 super(new NoLocaleSqliteContext(context), LauncherFiles.LAUNCHER_DB,
531 null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800532 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700533 mProvider = provider;
534
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700535 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700536
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700537 // Table creation sometimes fails silently, which leads to a crash loop.
538 // This way, we will try to create a table every time after crash, so the device
539 // would eventually be able to recover.
540 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
541 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
542 // This operation is a no-op if the table already exists.
543 addFavoritesTable(getWritableDatabase(), true);
544 addWorkspacesTable(getWritableDatabase(), true);
545 }
546
Winson Chung3d503fb2011-07-13 17:25:49 -0700547 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
548 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700549 if (mMaxItemId == -1) {
550 mMaxItemId = initializeMaxItemId(getWritableDatabase());
551 }
552 if (mMaxScreenId == -1) {
553 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700554 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800555 }
556
Sunny Goyalf076eae2016-01-11 12:25:10 -0800557 /**
558 * Constructor used only in tests.
559 */
560 public DatabaseHelper(Context context, LauncherProvider provider, String tableName) {
Sunny Goyalbf67f3b2016-03-15 15:30:11 -0700561 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800562 mContext = context;
563 mProvider = provider;
564
565 mAppWidgetHost = null;
566 mMaxItemId = initializeMaxItemId(getWritableDatabase());
567 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
568 }
569
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700570 private boolean tableExists(String tableName) {
571 Cursor c = getReadableDatabase().query(
572 true, "sqlite_master", new String[] {"tbl_name"},
573 "tbl_name = ?", new String[] {tableName},
574 null, null, null, null, null);
575 try {
576 return c.getCount() > 0;
577 } finally {
578 c.close();
579 }
580 }
581
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 @Override
583 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800584 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700585
Adam Cohendcd297f2013-06-18 13:13:40 -0700586 mMaxItemId = 1;
587 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700588
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700589 addFavoritesTable(db, false);
590 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800591
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700592 // Database was just created, so wipe any previous widgets
593 if (mAppWidgetHost != null) {
594 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700595 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700597
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800598 // Fresh and clean launcher DB.
599 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800600 onEmptyDbCreated();
601 }
602
603 /**
604 * Overriden in tests.
605 */
606 protected void onEmptyDbCreated() {
607 // Set the flag for empty DB
608 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700609
610 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800611 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
612 mContext);
613 }
614
615 protected long getDefaultUserSerial() {
616 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
617 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800618 }
619
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700620 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700621 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700622 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
623 "_id INTEGER PRIMARY KEY," +
624 "title TEXT," +
625 "intent TEXT," +
626 "container INTEGER," +
627 "screen INTEGER," +
628 "cellX INTEGER," +
629 "cellY INTEGER," +
630 "spanX INTEGER," +
631 "spanY INTEGER," +
632 "itemType INTEGER," +
633 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
634 "isShortcut INTEGER," +
635 "iconType INTEGER," +
636 "iconPackage TEXT," +
637 "iconResource TEXT," +
638 "icon BLOB," +
639 "uri TEXT," +
640 "displayMode INTEGER," +
641 "appWidgetProvider TEXT," +
642 "modified INTEGER NOT NULL DEFAULT 0," +
643 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800644 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700645 "rank INTEGER NOT NULL DEFAULT 0," +
646 "options INTEGER NOT NULL DEFAULT 0" +
647 ");");
648 }
649
650 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
651 String ifNotExists = optional ? " IF NOT EXISTS " : "";
652 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800653 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400654 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
655 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700656 ");");
657 }
658
Adam Cohen119285e2014-04-02 16:59:08 -0700659 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700660 // Delete items directly on the workspace who's screen id doesn't exist
661 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
662 // AND container = -100"
663 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
664 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700665 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700666 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
667 " AND " +
668 LauncherSettings.Favorites.CONTAINER + " = " +
669 LauncherSettings.Favorites.CONTAINER_DESKTOP;
670 db.execSQL(removeOrphanedDesktopItems);
671
672 // Delete items contained in folders which no longer exist (after above statement)
673 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
674 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
675 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
676 " WHERE " +
677 LauncherSettings.Favorites.CONTAINER + " <> " +
678 LauncherSettings.Favorites.CONTAINER_DESKTOP +
679 " AND "
680 + LauncherSettings.Favorites.CONTAINER + " <> " +
681 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
682 " AND "
683 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
684 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
685 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
686 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
687 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700688 }
689
Winson Chungc763c4e2013-07-19 13:49:06 -0700690 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700691 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700692 }
693
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800694 @Override
695 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700696 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 switch (oldVersion) {
698 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800699 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800700 case 12: {
701 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
702 // to persist workspace screens and their relative order.
703 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700704 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800705 }
706 case 13: {
707 db.beginTransaction();
708 try {
709 // Insert new column for holding widget provider name
710 db.execSQL("ALTER TABLE favorites " +
711 "ADD COLUMN appWidgetProvider TEXT;");
712 db.setTransactionSuccessful();
713 } catch (SQLException ex) {
714 Log.e(TAG, ex.getMessage(), ex);
715 // Old version remains, which means we wipe old data
716 break;
717 } finally {
718 db.endTransaction();
719 }
720 }
721 case 14: {
722 db.beginTransaction();
723 try {
724 // Insert new column for holding update timestamp
725 db.execSQL("ALTER TABLE favorites " +
726 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
727 db.execSQL("ALTER TABLE workspaceScreens " +
728 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
729 db.setTransactionSuccessful();
730 } catch (SQLException ex) {
731 Log.e(TAG, ex.getMessage(), ex);
732 // Old version remains, which means we wipe old data
733 break;
734 } finally {
735 db.endTransaction();
736 }
737 }
738 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700739 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800740 // Old version remains, which means we wipe old data
741 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 }
743 }
744 case 16: {
745 // We use the db version upgrade here to identify users who may not have seen
746 // clings yet (because they weren't available), but for whom the clings are now
747 // available (tablet users). Because one of the possible cling flows (migration)
748 // is very destructive (wipes out workspaces), we want to prevent this from showing
749 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800750 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 }
752 case 17: {
753 // No-op
754 }
755 case 18: {
756 // Due to a data loss bug, some users may have items associated with screen ids
757 // which no longer exist. Since this can cause other problems, and since the user
758 // will never see these items anyway, we use database upgrade as an opportunity to
759 // clean things up.
760 removeOrphanedItems(db);
761 }
762 case 19: {
763 // Add userId column
764 if (!addProfileColumn(db)) {
765 // Old version remains, which means we wipe old data
766 break;
767 }
768 }
769 case 20:
770 if (!updateFolderItemsRank(db, true)) {
771 break;
772 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800773 case 21:
774 // Recreate workspace table with screen id a primary key
775 if (!recreateWorkspaceTable(db)) {
776 break;
777 }
778 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700779 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
780 // Old version remains, which means we wipe old data
781 break;
782 }
783 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700784 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700785 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700786 case 24:
787 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700788 case 25:
789 convertShortcutsToLauncherActivities(db);
790 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800791 // DB Upgraded successfully
792 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400793 }
794 }
795
Sunny Goyala2cc6242015-01-14 14:23:02 -0800796 // DB was not upgraded
797 Log.w(TAG, "Destroying all old data.");
798 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800799 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800800
Adam Cohen9b1d0622014-05-21 19:01:57 -0700801 @Override
802 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
803 // This shouldn't happen -- throw our hands up in the air and start over.
804 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
805 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700806 createEmptyDB(db);
807 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700808
Sunny Goyal42de82f2014-09-26 22:09:29 -0700809 /**
810 * Clears all the data for a fresh start.
811 */
812 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700813 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
814 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
815 onCreate(db);
816 }
817
Sunny Goyald2f38192015-02-25 10:46:34 -0800818 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700819 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
820 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
821 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700822 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700823 db.beginTransaction();
824 Cursor c = null;
825 SQLiteStatement updateStmt = null;
826
827 try {
828 // Only consider the primary user as other users can't have a shortcut.
829 long userSerial = UserManagerCompat.getInstance(mContext)
830 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
831 c = db.query(TABLE_FAVORITES, new String[] {
832 Favorites._ID,
833 Favorites.INTENT,
834 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
835 null, null, null, null);
836
837 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
838 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
839
840 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
841 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
842
843 while (c.moveToNext()) {
844 String intentDescription = c.getString(intentIndex);
845 Intent intent;
846 try {
847 intent = Intent.parseUri(intentDescription, 0);
848 } catch (URISyntaxException e) {
849 Log.e(TAG, "Unable to parse intent", e);
850 continue;
851 }
852
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700853 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700854 continue;
855 }
856
857 long id = c.getLong(idIndex);
858 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700859 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700860 }
861 db.setTransactionSuccessful();
862 } catch (SQLException ex) {
863 Log.w(TAG, "Error deduping shortcuts", ex);
864 } finally {
865 db.endTransaction();
866 if (c != null) {
867 c.close();
868 }
869 if (updateStmt != null) {
870 updateStmt.close();
871 }
872 }
873 }
874
875 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800876 * Recreates workspace table and migrates data to the new table.
877 */
878 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
879 db.beginTransaction();
880 try {
881 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
882 new String[] {LauncherSettings.WorkspaceScreens._ID},
883 null, null, null, null,
884 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
885 ArrayList<Long> sortedIDs = new ArrayList<Long>();
886 long maxId = 0;
887 try {
888 while (c.moveToNext()) {
889 Long id = c.getLong(0);
890 if (!sortedIDs.contains(id)) {
891 sortedIDs.add(id);
892 maxId = Math.max(maxId, id);
893 }
894 }
895 } finally {
896 c.close();
897 }
898
899 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700900 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800901
902 // Add all screen ids back
903 int total = sortedIDs.size();
904 for (int i = 0; i < total; i++) {
905 ContentValues values = new ContentValues();
906 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
907 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
908 addModifiedTime(values);
909 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
910 }
911 db.setTransactionSuccessful();
912 mMaxScreenId = maxId;
913 } catch (SQLException ex) {
914 // Old version remains, which means we wipe old data
915 Log.e(TAG, ex.getMessage(), ex);
916 return false;
917 } finally {
918 db.endTransaction();
919 }
920 return true;
921 }
922
Adam Cohen091440a2015-03-18 14:16:05 -0700923 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800924 db.beginTransaction();
925 try {
926 if (addRankColumn) {
927 // Insert new column for holding rank
928 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
929 }
930
931 // Get a map for folder ID to folder width
932 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
933 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
934 + " GROUP BY container;",
935 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
936
937 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800938 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
939 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800940 new Object[] {c.getLong(1) + 1, c.getLong(0)});
941 }
942
943 c.close();
944 db.setTransactionSuccessful();
945 } catch (SQLException ex) {
946 // Old version remains, which means we wipe old data
947 Log.e(TAG, ex.getMessage(), ex);
948 return false;
949 } finally {
950 db.endTransaction();
951 }
952 return true;
953 }
954
Kenny Guyed131872014-04-30 03:02:21 +0100955 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700956 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
957 // Default to the serial number of this user, for older
958 // shortcuts.
959 long userSerialNumber = userManager.getSerialNumberForUser(
960 UserHandleCompat.myUserHandle());
961 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
962 }
963
964 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100965 db.beginTransaction();
966 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700967 db.execSQL("ALTER TABLE favorites ADD COLUMN "
968 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100969 db.setTransactionSuccessful();
970 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100971 Log.e(TAG, ex.getMessage(), ex);
972 return false;
973 } finally {
974 db.endTransaction();
975 }
976 return true;
977 }
978
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700979 // Generates a new ID to use for an object in your database. This method should be only
980 // called from the main UI thread. As an exception, we do call it when we call the
981 // constructor from the worker thread; however, this doesn't extend until after the
982 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
983 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700984 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700985 public long generateNewItemId() {
986 if (mMaxItemId < 0) {
987 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700988 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700989 mMaxItemId += 1;
990 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700991 }
992
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700993 @Override
994 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
995 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
996 }
997
Chris Wren5dee7af2013-12-20 17:22:11 -0500998 public void checkId(String table, ContentValues values) {
999 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1000 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1001 mMaxScreenId = Math.max(id, mMaxScreenId);
1002 } else {
1003 mMaxItemId = Math.max(id, mMaxItemId);
1004 }
1005 }
1006
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001008 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -07001009 }
1010
1011 // Generates a new ID to use for an workspace screen in your database. This method
1012 // should be only called from the main UI thread. As an exception, we do call it when we
1013 // call the constructor from the worker thread; however, this doesn't extend until after the
1014 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1015 // after that point
1016 public long generateNewScreenId() {
1017 if (mMaxScreenId < 0) {
1018 throw new RuntimeException("Error: max screen id was not initialized");
1019 }
1020 mMaxScreenId += 1;
1021 return mMaxScreenId;
1022 }
1023
Adam Cohendcd297f2013-06-18 13:13:40 -07001024 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001025 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001026 }
1027
Adam Cohen091440a2015-03-18 14:16:05 -07001028 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001029 // 1. Ensure that externally added items have a valid item id
1030 long id = generateNewItemId();
1031 values.put(LauncherSettings.Favorites._ID, id);
1032
1033 // 2. In the case of an app widget, and if no app widget id is specified, we
1034 // attempt allocate and bind the widget.
1035 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1036 if (itemType != null &&
1037 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1038 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1039
1040 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1041 ComponentName cn = ComponentName.unflattenFromString(
1042 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1043
1044 if (cn != null) {
1045 try {
1046 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001047 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001048 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001049 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001050 }
1051 } catch (RuntimeException e) {
1052 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001053 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001054 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001055 } else {
1056 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001057 }
1058 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001059
1060 // Add screen id if not present
1061 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1062 if (!addScreenIdIfNecessary(screenId)) {
1063 return false;
1064 }
Adam Cohena043fa82014-07-23 14:49:38 -07001065 return true;
1066 }
1067
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001068 // Returns true of screen id exists, or if successfully added
1069 private boolean addScreenIdIfNecessary(long screenId) {
1070 if (!hasScreenId(screenId)) {
1071 int rank = getMaxScreenRank() + 1;
1072
1073 ContentValues v = new ContentValues();
1074 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1075 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1076 if (dbInsertAndCheck(this, getWritableDatabase(),
1077 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1078 return false;
1079 }
1080 }
1081 return true;
1082 }
1083
1084 private boolean hasScreenId(long screenId) {
1085 SQLiteDatabase db = getWritableDatabase();
1086 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1087 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1088 if (c != null) {
1089 int count = c.getCount();
1090 c.close();
1091 return count > 0;
1092 } else {
1093 return false;
1094 }
1095 }
1096
1097 private int getMaxScreenRank() {
1098 SQLiteDatabase db = getWritableDatabase();
1099 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1100 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1101
1102 // get the result
1103 final int maxRankIndex = 0;
1104 int rank = -1;
1105 if (c != null && c.moveToNext()) {
1106 rank = c.getInt(maxRankIndex);
1107 }
1108 if (c != null) {
1109 c.close();
1110 }
1111
1112 return rank;
1113 }
1114
Adam Cohen091440a2015-03-18 14:16:05 -07001115 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001116 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001117 // TODO: Use multiple loaders with fall-back and transaction.
1118 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001119
1120 // Add the screens specified by the items above
1121 Collections.sort(screenIds);
1122 int rank = 0;
1123 ContentValues values = new ContentValues();
1124 for (Long id : screenIds) {
1125 values.clear();
1126 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1127 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1128 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1129 throw new RuntimeException("Failed initialize screen table"
1130 + "from default layout");
1131 }
1132 rank++;
1133 }
1134
1135 // Ensure that the max ids are initialized
1136 mMaxItemId = initializeMaxItemId(db);
1137 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001138
Adam Cohen71483f42014-05-15 14:04:01 -07001139 return count;
1140 }
1141
Adam Cohen091440a2015-03-18 14:16:05 -07001142 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001143 final ContentResolver resolver = mContext.getContentResolver();
1144 Cursor c = null;
1145 int count = 0;
1146 int curScreen = 0;
1147
1148 try {
1149 c = resolver.query(uri, null, null, null, "title ASC");
1150 } catch (Exception e) {
1151 // Ignore
1152 }
1153
Dan Sandlerd5024042014-01-09 15:01:33 -05001154 // We already have a favorites database in the old provider
1155 if (c != null) {
1156 try {
1157 if (c.getCount() > 0) {
1158 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1159 final int intentIndex
1160 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1161 final int titleIndex
1162 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1163 final int iconTypeIndex
1164 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1165 final int iconIndex
1166 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1167 final int iconPackageIndex
1168 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1169 final int iconResourceIndex
1170 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1171 final int containerIndex
1172 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1173 final int itemTypeIndex
1174 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1175 final int screenIndex
1176 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1177 final int cellXIndex
1178 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1179 final int cellYIndex
1180 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001181 final int profileIndex
1182 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001183
1184 int i = 0;
1185 int curX = 0;
1186 int curY = 0;
1187
1188 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001189 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1190 final int width = (int) profile.numColumns;
1191 final int height = (int) profile.numRows;
1192 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001193
1194 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1195
Adam Cohen72960972014-01-15 18:13:55 -08001196 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1197 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001198 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001199
1200 while (c.moveToNext()) {
1201 final int itemType = c.getInt(itemTypeIndex);
1202 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1203 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1204 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1205 continue;
1206 }
1207
1208 final int cellX = c.getInt(cellXIndex);
1209 final int cellY = c.getInt(cellYIndex);
1210 final int screen = c.getInt(screenIndex);
1211 int container = c.getInt(containerIndex);
1212 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001213
1214 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1215 UserHandleCompat userHandle;
1216 final long userSerialNumber;
1217 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1218 userSerialNumber = c.getInt(profileIndex);
1219 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1220 } else {
1221 // Default to the serial number of this user, for older
1222 // shortcuts.
1223 userHandle = UserHandleCompat.myUserHandle();
1224 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1225 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001226
1227 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001228 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001229 continue;
1230 }
1231
Dan Sandlerd5024042014-01-09 15:01:33 -05001232 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001233
1234 final Intent intent;
1235 final ComponentName cn;
1236 try {
1237 intent = Intent.parseUri(intentStr, 0);
1238 } catch (URISyntaxException e) {
1239 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001240 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001241 continue;
1242 }
1243
1244 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001245 if (TextUtils.isEmpty(intentStr)) {
1246 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001247 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001248 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001249 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001250 !LauncherModel.isValidPackageActivity(mContext, cn,
1251 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001252 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001253 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001254 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001255 } else if (container ==
1256 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1257 // Dedupe icons directly on the workspace
1258
Adam Cohen556f6132014-01-15 15:18:08 -08001259 // Canonicalize
1260 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001261 // does not, so we clear that out to keep them the same.
1262 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001263 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001264 int flags = intent.getFlags();
1265 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001266 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001267 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001268 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001269 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001270 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001271 } else {
1272 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001273 }
1274 }
1275 }
1276
1277 ContentValues values = new ContentValues(c.getColumnCount());
1278 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1279 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1280 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1281 values.put(LauncherSettings.Favorites.ICON_TYPE,
1282 c.getInt(iconTypeIndex));
1283 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1284 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1285 c.getString(iconPackageIndex));
1286 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1287 c.getString(iconResourceIndex));
1288 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1289 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001290 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001291
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001292 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1293 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001294 }
1295
1296 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1297 // In a folder or in the hotseat, preserve position
1298 values.put(LauncherSettings.Favorites.SCREEN, screen);
1299 values.put(LauncherSettings.Favorites.CELLX, cellX);
1300 values.put(LauncherSettings.Favorites.CELLY, cellY);
1301 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001302 // For items contained directly on one of the workspace screen,
1303 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001304 }
1305
1306 values.put(LauncherSettings.Favorites.CONTAINER, container);
1307
Adam Cohen72960972014-01-15 18:13:55 -08001308 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1309 shortcuts.add(values);
1310 } else {
1311 folders.add(values);
1312 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001313 }
1314
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001315 // Now that we have all the hotseat icons, let's go through them left-right
1316 // and assign valid locations for them in the new hotseat
1317 final int N = hotseat.size();
1318 for (int idx=0; idx<N; idx++) {
1319 int hotseatX = hotseat.keyAt(idx);
1320 ContentValues values = hotseat.valueAt(idx);
1321
Adam Cohen2e6da152015-05-06 11:42:25 -07001322 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001323 // let's drop this in the next available hole in the hotseat
1324 while (++hotseatX < hotseatWidth) {
1325 if (hotseat.get(hotseatX) == null) {
1326 // found a spot! move it here
1327 values.put(LauncherSettings.Favorites.SCREEN,
1328 hotseatX);
1329 break;
1330 }
1331 }
1332 }
1333 if (hotseatX >= hotseatWidth) {
1334 // no room for you in the hotseat? it's off to the desktop with you
1335 values.put(LauncherSettings.Favorites.CONTAINER,
1336 Favorites.CONTAINER_DESKTOP);
1337 }
1338 }
1339
Adam Cohen72960972014-01-15 18:13:55 -08001340 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1341 // Folders first
1342 allItems.addAll(folders);
1343 // Then shortcuts
1344 allItems.addAll(shortcuts);
1345
1346 // Layout all the folders
1347 for (ContentValues values: allItems) {
1348 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1349 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1350 // Hotseat items and folder items have already had their
1351 // location information set. Nothing to be done here.
1352 continue;
1353 }
1354 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1355 values.put(LauncherSettings.Favorites.CELLX, curX);
1356 values.put(LauncherSettings.Favorites.CELLY, curY);
1357 curX = (curX + 1) % width;
1358 if (curX == 0) {
1359 curY = (curY + 1);
1360 }
1361 // Leave the last row of icons blank on every screen
1362 if (curY == height - 1) {
1363 curScreen = (int) generateNewScreenId();
1364 curY = 0;
1365 }
1366 }
1367
1368 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001369 db.beginTransaction();
1370 try {
Adam Cohen72960972014-01-15 18:13:55 -08001371 for (ContentValues row: allItems) {
1372 if (row == null) continue;
1373 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001374 < 0) {
1375 return;
1376 } else {
1377 count++;
1378 }
1379 }
1380 db.setTransactionSuccessful();
1381 } finally {
1382 db.endTransaction();
1383 }
1384 }
1385
1386 db.beginTransaction();
1387 try {
1388 for (i=0; i<=curScreen; i++) {
1389 final ContentValues values = new ContentValues();
1390 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1391 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1392 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1393 < 0) {
1394 return;
1395 }
1396 }
1397 db.setTransactionSuccessful();
1398 } finally {
1399 db.endTransaction();
1400 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001401
1402 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001403 }
1404 } finally {
1405 c.close();
1406 }
1407 }
1408
Sunny Goyala1365452015-10-01 15:46:24 -07001409 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1410 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001411
1412 // ensure that new screens are created to hold these icons
1413 setFlagJustLoadedOldDb();
1414
1415 // Update max IDs; very important since we just grabbed IDs from another database
1416 mMaxItemId = initializeMaxItemId(db);
1417 mMaxScreenId = initializeMaxScreenId(db);
1418 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1419 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001420 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001421
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001422 /**
1423 * @return the max _id in the provided table.
1424 */
Adam Cohen091440a2015-03-18 14:16:05 -07001425 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001426 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1427 // get the result
1428 long id = -1;
1429 if (c != null && c.moveToNext()) {
1430 id = c.getLong(0);
1431 }
1432 if (c != null) {
1433 c.close();
1434 }
1435
1436 if (id == -1) {
1437 throw new RuntimeException("Error: could not query max id in " + table);
1438 }
1439
1440 return id;
1441 }
1442
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001443 static class SqlArguments {
1444 public final String table;
1445 public final String where;
1446 public final String[] args;
1447
1448 SqlArguments(Uri url, String where, String[] args) {
1449 if (url.getPathSegments().size() == 1) {
1450 this.table = url.getPathSegments().get(0);
1451 this.where = where;
1452 this.args = args;
1453 } else if (url.getPathSegments().size() != 2) {
1454 throw new IllegalArgumentException("Invalid URI: " + url);
1455 } else if (!TextUtils.isEmpty(where)) {
1456 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1457 } else {
1458 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001459 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001460 this.args = null;
1461 }
1462 }
1463
1464 SqlArguments(Uri url) {
1465 if (url.getPathSegments().size() == 1) {
1466 table = url.getPathSegments().get(0);
1467 where = null;
1468 args = null;
1469 } else {
1470 throw new IllegalArgumentException("Invalid URI: " + url);
1471 }
1472 }
1473 }
Adam Cohen72960972014-01-15 18:13:55 -08001474}