blob: 53026ac5a4f37c63ca75a3fe3fe6f1c91380a5fb [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;
Tony Wickham827cef22016-03-17 15:39:39 -070056import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070058import com.android.launcher3.util.NoLocaleSqliteContext;
Adam Cohen091440a2015-03-18 14:16:05 -070059import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070060
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 Goyald3849d12015-10-29 10:28:32 -070080 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070081 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyalf076eae2016-01-11 12:25:10 -080082 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 return true;
88 }
89
Sunny Goyald3849d12015-10-29 10:28:32 -070090 /**
91 * Sets a provider listener.
92 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070093 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070094 synchronized (LISTENER_LOCK) {
95 mListener = listener;
96 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 }
98
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099 @Override
100 public String getType(Uri uri) {
101 SqlArguments args = new SqlArguments(uri, null, null);
102 if (TextUtils.isEmpty(args.where)) {
103 return "vnd.android.cursor.dir/" + args.table;
104 } else {
105 return "vnd.android.cursor.item/" + args.table;
106 }
107 }
108
Sunny Goyalf076eae2016-01-11 12:25:10 -0800109 /**
110 * Overridden in tests
111 */
112 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700113 if (mOpenHelper == null) {
114 mOpenHelper = new DatabaseHelper(getContext(), this);
115 }
116 }
117
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800118 @Override
119 public Cursor query(Uri uri, String[] projection, String selection,
120 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700121 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122
123 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
124 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
125 qb.setTables(args.table);
126
Romain Guy73b979d2009-06-09 12:57:21 -0700127 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
129 result.setNotificationUri(getContext().getContentResolver(), uri);
130
131 return result;
132 }
133
Adam Cohen091440a2015-03-18 14:16:05 -0700134 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500136 if (values == null) {
137 throw new RuntimeException("Error: attempting to insert null values");
138 }
Adam Cohen71483f42014-05-15 14:04:01 -0700139 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 throw new RuntimeException("Error: attempting to add item without specifying an id");
141 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500142 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700143 return db.insert(table, nullColumnHack, values);
144 }
145
Sunny Goyald1064182015-08-13 12:08:30 -0700146 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700147 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700148 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
149 if (app != null) {
150 app.reloadWorkspace();
151 }
152 }
153 }
154
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 @Override
156 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800158 SqlArguments args = new SqlArguments(uri);
159
Sunny Goyald1064182015-08-13 12:08:30 -0700160 // In very limited cases, we support system|signature permission apps to modify the db.
161 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700162 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
163 return null;
164 }
165 }
166
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400168 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700169 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800170 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171
172 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700173 notifyListeners();
174
Sunny Goyalc74e4192015-09-08 14:01:03 -0700175 if (Utilities.ATLEAST_MARSHMALLOW) {
176 reloadLauncherIfExternal();
177 } else {
178 // Deprecated behavior to support legacy devices which rely on provider callbacks.
179 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
180 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
181 app.reloadWorkspace();
182 }
183
184 String notify = uri.getQueryParameter("notify");
185 if (notify == null || "true".equals(notify)) {
186 getContext().getContentResolver().notifyChange(uri, null);
187 }
188 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 return uri;
190 }
191
192 @Override
193 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700194 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 SqlArguments args = new SqlArguments(uri);
196
197 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
198 db.beginTransaction();
199 try {
200 int numValues = values.length;
201 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400202 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700203 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
204 return 0;
205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 }
207 db.setTransactionSuccessful();
208 } finally {
209 db.endTransaction();
210 }
211
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700212 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700213 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214 return values.length;
215 }
216
217 @Override
Yura085c8532014-02-11 15:15:29 +0000218 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
219 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700220 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000221 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
222 db.beginTransaction();
223 try {
224 ContentProviderResult[] result = super.applyBatch(operations);
225 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700226 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000227 return result;
228 } finally {
229 db.endTransaction();
230 }
231 }
232
233 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700235 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
237
238 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
239 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700240 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241
Sunny Goyald1064182015-08-13 12:08:30 -0700242 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800243 return count;
244 }
245
246 @Override
247 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700248 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800249 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
250
Chris Wren1ada10d2013-09-13 18:01:38 -0400251 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800252 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
253 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700254 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800255
Sunny Goyald1064182015-08-13 12:08:30 -0700256 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800257 return count;
258 }
259
Sunny Goyal7779d622015-06-11 16:18:39 -0700260 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700261 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700262 if (Binder.getCallingUid() != Process.myUid()) {
263 return null;
264 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700265 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700266
267 switch (method) {
268 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
269 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800270 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
271 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
272 Utilities.isAllowRotationPrefEnabled(getContext()));
273 } else {
274 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
275 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
276 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
277 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700278 return result;
279 }
280 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
Tony Wickham827cef22016-03-17 15:39:39 -0700281 final boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700282 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyalb171e562016-01-21 16:41:54 -0800283 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
284 LauncherBackupAgentHelper.dataChanged(getContext());
285 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700286 Bundle result = new Bundle();
287 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
288 return result;
289 }
Tony Wickham827cef22016-03-17 15:39:39 -0700290 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
291 String extractedColors = extras.getString(
292 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
293 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
294 Utilities.getPrefs(getContext()).edit()
295 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
296 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
297 .apply();
298 new MainThreadExecutor().execute(new Runnable() {
299 @Override
300 public void run() {
301 synchronized (LISTENER_LOCK) {
302 if (mListener != null) {
303 mListener.onExtractedColorsChanged();
304 }
305 }
306
307 }
308 });
309 Bundle result = new Bundle();
310 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
311 return result;
312 }
Sunny Goyald2497482015-09-22 18:24:19 -0700313 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
314 clearFlagEmptyDbCreated();
315 return null;
316 }
317 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
318 Bundle result = new Bundle();
319 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
320 return result;
321 }
322 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
323 Bundle result = new Bundle();
324 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
325 return result;
326 }
327 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
328 Bundle result = new Bundle();
329 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
330 return result;
331 }
332 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
333 createEmptyDB();
334 return null;
335 }
336 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
337 loadDefaultFavoritesIfNecessary();
338 return null;
339 }
340 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
341 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
342 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
343 return null;
344 }
345 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
346 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
347 return null;
348 }
349 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
350 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
351 return null;
352 }
353 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800354 // Are you sure? (y/n)
355 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700356 return null;
357 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700358 }
359 return null;
360 }
361
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700362 /**
363 * Deletes any empty folder from the DB.
364 * @return Ids of deleted folders.
365 */
Sunny Goyald2497482015-09-22 18:24:19 -0700366 private ArrayList<Long> deleteEmptyFolders() {
367 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700368 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
369 db.beginTransaction();
370 try {
371 // Select folders whose id do not match any container value.
372 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
373 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
374 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
375 LauncherSettings.Favorites.CONTAINER + " FROM "
376 + TABLE_FAVORITES + ")";
377 Cursor c = db.query(TABLE_FAVORITES,
378 new String[] {LauncherSettings.Favorites._ID},
379 selection, null, null, null, null);
380 while (c.moveToNext()) {
381 folderIds.add(c.getLong(0));
382 }
383 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700384 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700385 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
386 LauncherSettings.Favorites._ID, folderIds), null);
387 }
388 db.setTransactionSuccessful();
389 } catch (SQLException ex) {
390 Log.e(TAG, ex.getMessage(), ex);
391 folderIds.clear();
392 } finally {
393 db.endTransaction();
394 }
395 return folderIds;
396 }
397
Sunny Goyalf076eae2016-01-11 12:25:10 -0800398 /**
399 * Overridden in tests
400 */
401 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400402 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400403 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700404 synchronized (LISTENER_LOCK) {
405 if (mListener != null) {
406 mListener.onLauncherProviderChange();
407 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700408 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400409 }
410
Adam Cohen091440a2015-03-18 14:16:05 -0700411 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400412 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800413 }
414
Brian Muramatsu5524b492012-10-02 16:55:54 -0700415 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700416 * Clears all the data for a fresh start.
417 */
Sunny Goyald2497482015-09-22 18:24:19 -0700418 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700419 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
420 }
421
Sunny Goyald2497482015-09-22 18:24:19 -0700422 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700423 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700424 }
425
Sunny Goyal42de82f2014-09-26 22:09:29 -0700426 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700427 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700428 * 1) From the app restrictions
429 * 2) From a package provided by play store
430 * 3) From a partner configuration APK, already in the system image
431 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700432 */
Sunny Goyald2497482015-09-22 18:24:19 -0700433 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700434 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700435
Winson Chungc763c4e2013-07-19 13:49:06 -0700436 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500437 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200438
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700439 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
440 if (loader == null) {
441 loader = AutoInstallsLayout.get(getContext(),
442 mOpenHelper.mAppWidgetHost, mOpenHelper);
443 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700444 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700445 final Partner partner = Partner.get(getContext().getPackageManager());
446 if (partner != null && partner.hasDefaultLayout()) {
447 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700448 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700449 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700450 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700451 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
452 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700453 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700454 }
455 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700456
Sunny Goyal9d219682014-10-23 14:21:02 -0700457 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700458 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700459 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700460 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800461
462 // There might be some partially restored DB items, due to buggy restore logic in
463 // previous versions of launcher.
464 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700465 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700466 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
467 && usingExternallyProvidedLayout) {
468 // Unable to load external layout. Cleanup and load the internal layout.
469 createEmptyDB();
470 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
471 getDefaultLayoutParser());
472 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700473 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700474 }
475 }
476
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700477 /**
478 * Creates workspace loader from an XML resource listed in the app restrictions.
479 *
480 * @return the loader if the restrictions are set and the resource exists; null otherwise.
481 */
482 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
483 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
484 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700485 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700486 return null;
487 }
488
489 Context ctx = getContext();
490 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
491 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700492 if (bundle == null) {
493 return null;
494 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700495
Sunny Goyal35ca8732015-04-06 10:45:31 -0700496 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700497 if (packageName != null) {
498 try {
499 Resources targetResources = ctx.getPackageManager()
500 .getResourcesForApplication(packageName);
501 return AutoInstallsLayout.get(ctx, packageName, targetResources,
502 mOpenHelper.mAppWidgetHost, mOpenHelper);
503 } catch (NameNotFoundException e) {
504 Log.e(TAG, "Target package for restricted profile not found", e);
505 return null;
506 }
507 }
508 return null;
509 }
510
Sunny Goyal9d219682014-10-23 14:21:02 -0700511 private DefaultLayoutParser getDefaultLayoutParser() {
512 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700513 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700514 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
515 mOpenHelper, getContext().getResources(), defaultLayout);
516 }
517
Sunny Goyald3849d12015-10-29 10:28:32 -0700518 /**
519 * Send notification that we've deleted the {@link AppWidgetHost},
520 * probably as part of the initial database creation. The receiver may
521 * want to re-call {@link AppWidgetHost#startListening()} to ensure
522 * callbacks are correctly set.
523 */
524 @Thunk void notifyAppHostReset() {
525 new MainThreadExecutor().execute(new Runnable() {
526
527 @Override
528 public void run() {
529 synchronized (LISTENER_LOCK) {
530 if (mListener != null) {
531 mListener.onAppWidgetHostReset();
532 }
533 }
534 }
535 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500536 }
537
Sunny Goyalf076eae2016-01-11 12:25:10 -0800538 /**
539 * The class is subclassed in tests to create an in-memory db.
540 */
541 protected static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700542 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800543 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700544 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700545 private long mMaxItemId = -1;
546 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800547
Sunny Goyald3849d12015-10-29 10:28:32 -0700548 DatabaseHelper(Context context, LauncherProvider provider) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700549 this(context, provider, LauncherFiles.LAUNCHER_DB,
550 new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID));
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700551 // Table creation sometimes fails silently, which leads to a crash loop.
552 // This way, we will try to create a table every time after crash, so the device
553 // would eventually be able to recover.
554 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
555 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
556 // This operation is a no-op if the table already exists.
557 addFavoritesTable(getWritableDatabase(), true);
558 addWorkspacesTable(getWritableDatabase(), true);
559 }
560
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700561 initIds();
562 }
563
564 /**
565 * Constructor used only in tests.
566 */
567 public DatabaseHelper(
568 Context context, LauncherProvider provider, String tableName, AppWidgetHost host) {
569 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
570 mContext = context;
571 mProvider = provider;
572 mAppWidgetHost = host;
573 }
574
575 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700576 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
577 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700578 if (mMaxItemId == -1) {
579 mMaxItemId = initializeMaxItemId(getWritableDatabase());
580 }
581 if (mMaxScreenId == -1) {
582 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700583 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 }
585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 private boolean tableExists(String tableName) {
587 Cursor c = getReadableDatabase().query(
588 true, "sqlite_master", new String[] {"tbl_name"},
589 "tbl_name = ?", new String[] {tableName},
590 null, null, null, null, null);
591 try {
592 return c.getCount() > 0;
593 } finally {
594 c.close();
595 }
596 }
597
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800598 @Override
599 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800600 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700601
Adam Cohendcd297f2013-06-18 13:13:40 -0700602 mMaxItemId = 1;
603 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700604
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700605 addFavoritesTable(db, false);
606 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700608 // Database was just created, so wipe any previous widgets
609 if (mAppWidgetHost != null) {
610 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700611 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700613
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800614 // Fresh and clean launcher DB.
615 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800616 onEmptyDbCreated();
617 }
618
619 /**
620 * Overriden in tests.
621 */
622 protected void onEmptyDbCreated() {
623 // Set the flag for empty DB
624 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700625
626 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800627 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
628 mContext);
629 }
630
631 protected long getDefaultUserSerial() {
632 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
633 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634 }
635
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700636 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700637 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700638 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
639 "_id INTEGER PRIMARY KEY," +
640 "title TEXT," +
641 "intent TEXT," +
642 "container INTEGER," +
643 "screen INTEGER," +
644 "cellX INTEGER," +
645 "cellY INTEGER," +
646 "spanX INTEGER," +
647 "spanY INTEGER," +
648 "itemType INTEGER," +
649 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700650 "iconType INTEGER," +
651 "iconPackage TEXT," +
652 "iconResource TEXT," +
653 "icon BLOB," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700654 "appWidgetProvider TEXT," +
655 "modified INTEGER NOT NULL DEFAULT 0," +
656 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyalf076eae2016-01-11 12:25:10 -0800657 "profileId INTEGER DEFAULT " + getDefaultUserSerial() + "," +
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700658 "rank INTEGER NOT NULL DEFAULT 0," +
659 "options INTEGER NOT NULL DEFAULT 0" +
660 ");");
661 }
662
663 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
664 String ifNotExists = optional ? " IF NOT EXISTS " : "";
665 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800666 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400667 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
668 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700669 ");");
670 }
671
Adam Cohen119285e2014-04-02 16:59:08 -0700672 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700673 // Delete items directly on the workspace who's screen id doesn't exist
674 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
675 // AND container = -100"
676 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
677 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700678 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700679 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
680 " AND " +
681 LauncherSettings.Favorites.CONTAINER + " = " +
682 LauncherSettings.Favorites.CONTAINER_DESKTOP;
683 db.execSQL(removeOrphanedDesktopItems);
684
685 // Delete items contained in folders which no longer exist (after above statement)
686 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
687 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
688 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
689 " WHERE " +
690 LauncherSettings.Favorites.CONTAINER + " <> " +
691 LauncherSettings.Favorites.CONTAINER_DESKTOP +
692 " AND "
693 + LauncherSettings.Favorites.CONTAINER + " <> " +
694 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
695 " AND "
696 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
697 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
698 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
699 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
700 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700701 }
702
Winson Chungc763c4e2013-07-19 13:49:06 -0700703 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700704 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700705 }
706
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707 @Override
708 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700709 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800710 switch (oldVersion) {
711 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800712 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800713 case 12: {
714 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
715 // to persist workspace screens and their relative order.
716 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700717 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800718 }
719 case 13: {
720 db.beginTransaction();
721 try {
722 // Insert new column for holding widget provider name
723 db.execSQL("ALTER TABLE favorites " +
724 "ADD COLUMN appWidgetProvider TEXT;");
725 db.setTransactionSuccessful();
726 } catch (SQLException ex) {
727 Log.e(TAG, ex.getMessage(), ex);
728 // Old version remains, which means we wipe old data
729 break;
730 } finally {
731 db.endTransaction();
732 }
733 }
734 case 14: {
735 db.beginTransaction();
736 try {
737 // Insert new column for holding update timestamp
738 db.execSQL("ALTER TABLE favorites " +
739 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
740 db.execSQL("ALTER TABLE workspaceScreens " +
741 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
742 db.setTransactionSuccessful();
743 } catch (SQLException ex) {
744 Log.e(TAG, ex.getMessage(), ex);
745 // Old version remains, which means we wipe old data
746 break;
747 } finally {
748 db.endTransaction();
749 }
750 }
751 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700752 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 // Old version remains, which means we wipe old data
754 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 }
756 }
757 case 16: {
758 // We use the db version upgrade here to identify users who may not have seen
759 // clings yet (because they weren't available), but for whom the clings are now
760 // available (tablet users). Because one of the possible cling flows (migration)
761 // is very destructive (wipes out workspaces), we want to prevent this from showing
762 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800763 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 }
765 case 17: {
766 // No-op
767 }
768 case 18: {
769 // Due to a data loss bug, some users may have items associated with screen ids
770 // which no longer exist. Since this can cause other problems, and since the user
771 // will never see these items anyway, we use database upgrade as an opportunity to
772 // clean things up.
773 removeOrphanedItems(db);
774 }
775 case 19: {
776 // Add userId column
777 if (!addProfileColumn(db)) {
778 // Old version remains, which means we wipe old data
779 break;
780 }
781 }
782 case 20:
783 if (!updateFolderItemsRank(db, true)) {
784 break;
785 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800786 case 21:
787 // Recreate workspace table with screen id a primary key
788 if (!recreateWorkspaceTable(db)) {
789 break;
790 }
791 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700792 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
793 // Old version remains, which means we wipe old data
794 break;
795 }
796 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700797 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700798 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700799 case 24:
800 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700801 case 25:
802 convertShortcutsToLauncherActivities(db);
803 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 // DB Upgraded successfully
805 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400806 }
807 }
808
Sunny Goyala2cc6242015-01-14 14:23:02 -0800809 // DB was not upgraded
810 Log.w(TAG, "Destroying all old data.");
811 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800812 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800813
Adam Cohen9b1d0622014-05-21 19:01:57 -0700814 @Override
815 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
816 // This shouldn't happen -- throw our hands up in the air and start over.
817 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
818 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700819 createEmptyDB(db);
820 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700821
Sunny Goyal42de82f2014-09-26 22:09:29 -0700822 /**
823 * Clears all the data for a fresh start.
824 */
825 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700826 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
827 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
828 onCreate(db);
829 }
830
Sunny Goyald2f38192015-02-25 10:46:34 -0800831 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700832 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
833 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
834 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700835 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700836 db.beginTransaction();
837 Cursor c = null;
838 SQLiteStatement updateStmt = null;
839
840 try {
841 // Only consider the primary user as other users can't have a shortcut.
842 long userSerial = UserManagerCompat.getInstance(mContext)
843 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
844 c = db.query(TABLE_FAVORITES, new String[] {
845 Favorites._ID,
846 Favorites.INTENT,
847 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
848 null, null, null, null);
849
850 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
851 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
852
853 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
854 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
855
856 while (c.moveToNext()) {
857 String intentDescription = c.getString(intentIndex);
858 Intent intent;
859 try {
860 intent = Intent.parseUri(intentDescription, 0);
861 } catch (URISyntaxException e) {
862 Log.e(TAG, "Unable to parse intent", e);
863 continue;
864 }
865
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700866 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700867 continue;
868 }
869
870 long id = c.getLong(idIndex);
871 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700872 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700873 }
874 db.setTransactionSuccessful();
875 } catch (SQLException ex) {
876 Log.w(TAG, "Error deduping shortcuts", ex);
877 } finally {
878 db.endTransaction();
879 if (c != null) {
880 c.close();
881 }
882 if (updateStmt != null) {
883 updateStmt.close();
884 }
885 }
886 }
887
888 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800889 * Recreates workspace table and migrates data to the new table.
890 */
891 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
892 db.beginTransaction();
893 try {
894 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
895 new String[] {LauncherSettings.WorkspaceScreens._ID},
896 null, null, null, null,
897 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
898 ArrayList<Long> sortedIDs = new ArrayList<Long>();
899 long maxId = 0;
900 try {
901 while (c.moveToNext()) {
902 Long id = c.getLong(0);
903 if (!sortedIDs.contains(id)) {
904 sortedIDs.add(id);
905 maxId = Math.max(maxId, id);
906 }
907 }
908 } finally {
909 c.close();
910 }
911
912 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700913 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800914
915 // Add all screen ids back
916 int total = sortedIDs.size();
917 for (int i = 0; i < total; i++) {
918 ContentValues values = new ContentValues();
919 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
920 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
921 addModifiedTime(values);
922 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
923 }
924 db.setTransactionSuccessful();
925 mMaxScreenId = maxId;
926 } catch (SQLException ex) {
927 // Old version remains, which means we wipe old data
928 Log.e(TAG, ex.getMessage(), ex);
929 return false;
930 } finally {
931 db.endTransaction();
932 }
933 return true;
934 }
935
Adam Cohen091440a2015-03-18 14:16:05 -0700936 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800937 db.beginTransaction();
938 try {
939 if (addRankColumn) {
940 // Insert new column for holding rank
941 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
942 }
943
944 // Get a map for folder ID to folder width
945 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
946 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
947 + " GROUP BY container;",
948 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
949
950 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800951 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
952 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800953 new Object[] {c.getLong(1) + 1, c.getLong(0)});
954 }
955
956 c.close();
957 db.setTransactionSuccessful();
958 } catch (SQLException ex) {
959 // Old version remains, which means we wipe old data
960 Log.e(TAG, ex.getMessage(), ex);
961 return false;
962 } finally {
963 db.endTransaction();
964 }
965 return true;
966 }
967
Kenny Guyed131872014-04-30 03:02:21 +0100968 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700969 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
970 // Default to the serial number of this user, for older
971 // shortcuts.
972 long userSerialNumber = userManager.getSerialNumberForUser(
973 UserHandleCompat.myUserHandle());
974 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
975 }
976
977 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100978 db.beginTransaction();
979 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700980 db.execSQL("ALTER TABLE favorites ADD COLUMN "
981 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100982 db.setTransactionSuccessful();
983 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100984 Log.e(TAG, ex.getMessage(), ex);
985 return false;
986 } finally {
987 db.endTransaction();
988 }
989 return true;
990 }
991
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700992 // Generates a new ID to use for an object in your database. This method should be only
993 // called from the main UI thread. As an exception, we do call it when we call the
994 // constructor from the worker thread; however, this doesn't extend until after the
995 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
996 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700997 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 public long generateNewItemId() {
999 if (mMaxItemId < 0) {
1000 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 mMaxItemId += 1;
1003 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001004 }
1005
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001006 @Override
1007 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
1008 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
1009 }
1010
Chris Wren5dee7af2013-12-20 17:22:11 -05001011 public void checkId(String table, ContentValues values) {
1012 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1013 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1014 mMaxScreenId = Math.max(id, mMaxScreenId);
1015 } else {
1016 mMaxItemId = Math.max(id, mMaxItemId);
1017 }
1018 }
1019
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001021 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 }
1023
1024 // Generates a new ID to use for an workspace screen in your database. This method
1025 // should be only called from the main UI thread. As an exception, we do call it when we
1026 // call the constructor from the worker thread; however, this doesn't extend until after the
1027 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1028 // after that point
1029 public long generateNewScreenId() {
1030 if (mMaxScreenId < 0) {
1031 throw new RuntimeException("Error: max screen id was not initialized");
1032 }
1033 mMaxScreenId += 1;
1034 return mMaxScreenId;
1035 }
1036
Adam Cohendcd297f2013-06-18 13:13:40 -07001037 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001038 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001039 }
1040
Adam Cohen091440a2015-03-18 14:16:05 -07001041 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001042 // 1. Ensure that externally added items have a valid item id
1043 long id = generateNewItemId();
1044 values.put(LauncherSettings.Favorites._ID, id);
1045
1046 // 2. In the case of an app widget, and if no app widget id is specified, we
1047 // attempt allocate and bind the widget.
1048 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1049 if (itemType != null &&
1050 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1051 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1052
1053 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1054 ComponentName cn = ComponentName.unflattenFromString(
1055 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1056
1057 if (cn != null) {
1058 try {
1059 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001060 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001061 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001062 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001063 }
1064 } catch (RuntimeException e) {
1065 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001066 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001067 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001068 } else {
1069 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001070 }
1071 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001072
1073 // Add screen id if not present
1074 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1075 if (!addScreenIdIfNecessary(screenId)) {
1076 return false;
1077 }
Adam Cohena043fa82014-07-23 14:49:38 -07001078 return true;
1079 }
1080
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001081 // Returns true of screen id exists, or if successfully added
1082 private boolean addScreenIdIfNecessary(long screenId) {
1083 if (!hasScreenId(screenId)) {
1084 int rank = getMaxScreenRank() + 1;
1085
1086 ContentValues v = new ContentValues();
1087 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1088 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1089 if (dbInsertAndCheck(this, getWritableDatabase(),
1090 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1091 return false;
1092 }
1093 }
1094 return true;
1095 }
1096
1097 private boolean hasScreenId(long screenId) {
1098 SQLiteDatabase db = getWritableDatabase();
1099 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1100 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1101 if (c != null) {
1102 int count = c.getCount();
1103 c.close();
1104 return count > 0;
1105 } else {
1106 return false;
1107 }
1108 }
1109
1110 private int getMaxScreenRank() {
1111 SQLiteDatabase db = getWritableDatabase();
1112 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1113 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1114
1115 // get the result
1116 final int maxRankIndex = 0;
1117 int rank = -1;
1118 if (c != null && c.moveToNext()) {
1119 rank = c.getInt(maxRankIndex);
1120 }
1121 if (c != null) {
1122 c.close();
1123 }
1124
1125 return rank;
1126 }
1127
Adam Cohen091440a2015-03-18 14:16:05 -07001128 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001129 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001130 // TODO: Use multiple loaders with fall-back and transaction.
1131 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001132
1133 // Add the screens specified by the items above
1134 Collections.sort(screenIds);
1135 int rank = 0;
1136 ContentValues values = new ContentValues();
1137 for (Long id : screenIds) {
1138 values.clear();
1139 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1140 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1141 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1142 throw new RuntimeException("Failed initialize screen table"
1143 + "from default layout");
1144 }
1145 rank++;
1146 }
1147
1148 // Ensure that the max ids are initialized
1149 mMaxItemId = initializeMaxItemId(db);
1150 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001151
Adam Cohen71483f42014-05-15 14:04:01 -07001152 return count;
1153 }
1154
Adam Cohen091440a2015-03-18 14:16:05 -07001155 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001156 final ContentResolver resolver = mContext.getContentResolver();
1157 Cursor c = null;
1158 int count = 0;
1159 int curScreen = 0;
1160
1161 try {
1162 c = resolver.query(uri, null, null, null, "title ASC");
1163 } catch (Exception e) {
1164 // Ignore
1165 }
1166
Dan Sandlerd5024042014-01-09 15:01:33 -05001167 // We already have a favorites database in the old provider
1168 if (c != null) {
1169 try {
1170 if (c.getCount() > 0) {
1171 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1172 final int intentIndex
1173 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1174 final int titleIndex
1175 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1176 final int iconTypeIndex
1177 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1178 final int iconIndex
1179 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1180 final int iconPackageIndex
1181 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1182 final int iconResourceIndex
1183 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1184 final int containerIndex
1185 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1186 final int itemTypeIndex
1187 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1188 final int screenIndex
1189 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1190 final int cellXIndex
1191 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1192 final int cellYIndex
1193 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001194 final int profileIndex
1195 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001196
1197 int i = 0;
1198 int curX = 0;
1199 int curY = 0;
1200
1201 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001202 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1203 final int width = (int) profile.numColumns;
1204 final int height = (int) profile.numRows;
1205 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001206
1207 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1208
Adam Cohen72960972014-01-15 18:13:55 -08001209 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1210 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001211 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001212
1213 while (c.moveToNext()) {
1214 final int itemType = c.getInt(itemTypeIndex);
1215 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1216 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1217 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1218 continue;
1219 }
1220
1221 final int cellX = c.getInt(cellXIndex);
1222 final int cellY = c.getInt(cellYIndex);
1223 final int screen = c.getInt(screenIndex);
1224 int container = c.getInt(containerIndex);
1225 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001226
1227 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1228 UserHandleCompat userHandle;
1229 final long userSerialNumber;
1230 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1231 userSerialNumber = c.getInt(profileIndex);
1232 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1233 } else {
1234 // Default to the serial number of this user, for older
1235 // shortcuts.
1236 userHandle = UserHandleCompat.myUserHandle();
1237 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1238 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001239
1240 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001241 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001242 continue;
1243 }
1244
Dan Sandlerd5024042014-01-09 15:01:33 -05001245 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001246
1247 final Intent intent;
1248 final ComponentName cn;
1249 try {
1250 intent = Intent.parseUri(intentStr, 0);
1251 } catch (URISyntaxException e) {
1252 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001253 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001254 continue;
1255 }
1256
1257 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001258 if (TextUtils.isEmpty(intentStr)) {
1259 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001260 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001261 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001262 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001263 !LauncherModel.isValidPackageActivity(mContext, cn,
1264 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001265 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001266 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001267 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001268 } else if (container ==
1269 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1270 // Dedupe icons directly on the workspace
1271
Adam Cohen556f6132014-01-15 15:18:08 -08001272 // Canonicalize
1273 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001274 // does not, so we clear that out to keep them the same.
1275 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001276 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001277 int flags = intent.getFlags();
1278 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001279 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001280 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001281 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001282 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001283 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001284 } else {
1285 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001286 }
1287 }
1288 }
1289
1290 ContentValues values = new ContentValues(c.getColumnCount());
1291 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1292 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1293 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1294 values.put(LauncherSettings.Favorites.ICON_TYPE,
1295 c.getInt(iconTypeIndex));
1296 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1297 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1298 c.getString(iconPackageIndex));
1299 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1300 c.getString(iconResourceIndex));
1301 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1302 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001303 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001304
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001305 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1306 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001307 }
1308
1309 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1310 // In a folder or in the hotseat, preserve position
1311 values.put(LauncherSettings.Favorites.SCREEN, screen);
1312 values.put(LauncherSettings.Favorites.CELLX, cellX);
1313 values.put(LauncherSettings.Favorites.CELLY, cellY);
1314 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001315 // For items contained directly on one of the workspace screen,
1316 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001317 }
1318
1319 values.put(LauncherSettings.Favorites.CONTAINER, container);
1320
Adam Cohen72960972014-01-15 18:13:55 -08001321 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1322 shortcuts.add(values);
1323 } else {
1324 folders.add(values);
1325 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001326 }
1327
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001328 // Now that we have all the hotseat icons, let's go through them left-right
1329 // and assign valid locations for them in the new hotseat
1330 final int N = hotseat.size();
1331 for (int idx=0; idx<N; idx++) {
1332 int hotseatX = hotseat.keyAt(idx);
1333 ContentValues values = hotseat.valueAt(idx);
1334
Adam Cohen2e6da152015-05-06 11:42:25 -07001335 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001336 // let's drop this in the next available hole in the hotseat
1337 while (++hotseatX < hotseatWidth) {
1338 if (hotseat.get(hotseatX) == null) {
1339 // found a spot! move it here
1340 values.put(LauncherSettings.Favorites.SCREEN,
1341 hotseatX);
1342 break;
1343 }
1344 }
1345 }
1346 if (hotseatX >= hotseatWidth) {
1347 // no room for you in the hotseat? it's off to the desktop with you
1348 values.put(LauncherSettings.Favorites.CONTAINER,
1349 Favorites.CONTAINER_DESKTOP);
1350 }
1351 }
1352
Adam Cohen72960972014-01-15 18:13:55 -08001353 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1354 // Folders first
1355 allItems.addAll(folders);
1356 // Then shortcuts
1357 allItems.addAll(shortcuts);
1358
1359 // Layout all the folders
1360 for (ContentValues values: allItems) {
1361 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1362 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1363 // Hotseat items and folder items have already had their
1364 // location information set. Nothing to be done here.
1365 continue;
1366 }
1367 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1368 values.put(LauncherSettings.Favorites.CELLX, curX);
1369 values.put(LauncherSettings.Favorites.CELLY, curY);
1370 curX = (curX + 1) % width;
1371 if (curX == 0) {
1372 curY = (curY + 1);
1373 }
1374 // Leave the last row of icons blank on every screen
1375 if (curY == height - 1) {
1376 curScreen = (int) generateNewScreenId();
1377 curY = 0;
1378 }
1379 }
1380
1381 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001382 db.beginTransaction();
1383 try {
Adam Cohen72960972014-01-15 18:13:55 -08001384 for (ContentValues row: allItems) {
1385 if (row == null) continue;
1386 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001387 < 0) {
1388 return;
1389 } else {
1390 count++;
1391 }
1392 }
1393 db.setTransactionSuccessful();
1394 } finally {
1395 db.endTransaction();
1396 }
1397 }
1398
1399 db.beginTransaction();
1400 try {
1401 for (i=0; i<=curScreen; i++) {
1402 final ContentValues values = new ContentValues();
1403 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1404 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1405 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1406 < 0) {
1407 return;
1408 }
1409 }
1410 db.setTransactionSuccessful();
1411 } finally {
1412 db.endTransaction();
1413 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001414
1415 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001416 }
1417 } finally {
1418 c.close();
1419 }
1420 }
1421
Sunny Goyala1365452015-10-01 15:46:24 -07001422 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1423 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001424
1425 // ensure that new screens are created to hold these icons
1426 setFlagJustLoadedOldDb();
1427
1428 // Update max IDs; very important since we just grabbed IDs from another database
1429 mMaxItemId = initializeMaxItemId(db);
1430 mMaxScreenId = initializeMaxScreenId(db);
1431 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1432 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001433 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001434
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001435 /**
1436 * @return the max _id in the provided table.
1437 */
Adam Cohen091440a2015-03-18 14:16:05 -07001438 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001439 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1440 // get the result
1441 long id = -1;
1442 if (c != null && c.moveToNext()) {
1443 id = c.getLong(0);
1444 }
1445 if (c != null) {
1446 c.close();
1447 }
1448
1449 if (id == -1) {
1450 throw new RuntimeException("Error: could not query max id in " + table);
1451 }
1452
1453 return id;
1454 }
1455
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001456 static class SqlArguments {
1457 public final String table;
1458 public final String where;
1459 public final String[] args;
1460
1461 SqlArguments(Uri url, String where, String[] args) {
1462 if (url.getPathSegments().size() == 1) {
1463 this.table = url.getPathSegments().get(0);
1464 this.where = where;
1465 this.args = args;
1466 } else if (url.getPathSegments().size() != 2) {
1467 throw new IllegalArgumentException("Invalid URI: " + url);
1468 } else if (!TextUtils.isEmpty(where)) {
1469 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1470 } else {
1471 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001472 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001473 this.args = null;
1474 }
1475 }
1476
1477 SqlArguments(Uri url) {
1478 if (url.getPathSegments().size() == 1) {
1479 table = url.getPathSegments().get(0);
1480 where = null;
1481 args = null;
1482 } else {
1483 throw new IllegalArgumentException("Invalid URI: " + url);
1484 }
1485 }
1486 }
Adam Cohen72960972014-01-15 18:13:55 -08001487}