blob: f10099e0c78303aabd026646308b0608d6b26744 [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 Goyalb5b55c82016-05-10 12:28:59 -070045import android.os.Handler;
46import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Process;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070049import android.provider.BaseColumns;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050052import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070053
Sunny Goyal0fe505b2014-08-06 09:55:36 -070054import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
55import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070056import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010057import com.android.launcher3.compat.UserHandleCompat;
58import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070060import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070061import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070062import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070063import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070065
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070068import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050069import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070072 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080073 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
Sunny Goyal5c97f512015-05-19 16:03:28 -070075 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Sunny Goyale5bb7052015-07-27 14:36:07 -070077 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070078
Sunny Goyale87e6ab2014-11-21 22:42:53 -080079 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070081 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
82
Sunny Goyalb5b55c82016-05-10 12:28:59 -070083 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
84 private Handler mListenerHandler;
85
Sunny Goyalf076eae2016-01-11 12:25:10 -080086 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
88 @Override
89 public boolean onCreate() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -070090 mListenerHandler = new Handler(mListenerWrapper);
91
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093 return true;
94 }
95
Sunny Goyald3849d12015-10-29 10:28:32 -070096 /**
97 * Sets a provider listener.
98 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700100 Preconditions.assertUIThread();
101 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
Sunny Goyalf076eae2016-01-11 12:25:10 -0800114 /**
115 * Overridden in tests
116 */
117 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700118 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700119 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyald3849d12015-10-29 10:28:32 -0700120 }
121 }
122
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 @Override
124 public Cursor query(Uri uri, String[] projection, String selection,
125 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700126 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127
128 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
129 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
130 qb.setTables(args.table);
131
Romain Guy73b979d2009-06-09 12:57:21 -0700132 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
134 result.setNotificationUri(getContext().getContentResolver(), uri);
135
136 return result;
137 }
138
Adam Cohen091440a2015-03-18 14:16:05 -0700139 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500141 if (values == null) {
142 throw new RuntimeException("Error: attempting to insert null values");
143 }
Adam Cohen71483f42014-05-15 14:04:01 -0700144 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 throw new RuntimeException("Error: attempting to add item without specifying an id");
146 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500147 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 return db.insert(table, nullColumnHack, values);
149 }
150
Sunny Goyald1064182015-08-13 12:08:30 -0700151 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700152 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700153 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
154 if (app != null) {
155 app.reloadWorkspace();
156 }
157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700162 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 SqlArguments args = new SqlArguments(uri);
164
Sunny Goyald1064182015-08-13 12:08:30 -0700165 // In very limited cases, we support system|signature permission apps to modify the db.
166 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700167 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700168 return null;
169 }
170 }
171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800175 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700178 notifyListeners();
179
Sunny Goyalc74e4192015-09-08 14:01:03 -0700180 if (Utilities.ATLEAST_MARSHMALLOW) {
181 reloadLauncherIfExternal();
182 } else {
183 // Deprecated behavior to support legacy devices which rely on provider callbacks.
184 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
185 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
186 app.reloadWorkspace();
187 }
188
189 String notify = uri.getQueryParameter("notify");
190 if (notify == null || "true".equals(notify)) {
191 getContext().getContentResolver().notifyChange(uri, null);
192 }
193 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 return uri;
195 }
196
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700197 private boolean initializeExternalAdd(ContentValues values) {
198 // 1. Ensure that externally added items have a valid item id
199 long id = mOpenHelper.generateNewItemId();
200 values.put(LauncherSettings.Favorites._ID, id);
201
202 // 2. In the case of an app widget, and if no app widget id is specified, we
203 // attempt allocate and bind the widget.
204 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
205 if (itemType != null &&
206 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
207 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
208
209 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
210 ComponentName cn = ComponentName.unflattenFromString(
211 values.getAsString(Favorites.APPWIDGET_PROVIDER));
212
213 if (cn != null) {
214 try {
215 int appWidgetId = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID)
216 .allocateAppWidgetId();
217 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
218 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
219 return false;
220 }
221 } catch (RuntimeException e) {
222 Log.e(TAG, "Failed to initialize external widget", e);
223 return false;
224 }
225 } else {
226 return false;
227 }
228 }
229
230 // Add screen id if not present
231 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
232 SQLiteStatement stmp = null;
233 try {
234 stmp = mOpenHelper.getWritableDatabase().compileStatement(
235 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
236 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
237 stmp.bindLong(1, screenId);
238
239 ContentValues valuesInserted = new ContentValues();
240 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
241 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
242 return true;
243 } catch (Exception e) {
244 return false;
245 } finally {
246 Utilities.closeSilently(stmp);
247 }
248 }
249
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 @Override
251 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700252 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253 SqlArguments args = new SqlArguments(uri);
254
255 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
256 db.beginTransaction();
257 try {
258 int numValues = values.length;
259 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400260 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700261 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
262 return 0;
263 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 }
265 db.setTransactionSuccessful();
266 } finally {
267 db.endTransaction();
268 }
269
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700270 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700271 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 return values.length;
273 }
274
275 @Override
Yura085c8532014-02-11 15:15:29 +0000276 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
277 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700278 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000279 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
280 db.beginTransaction();
281 try {
282 ContentProviderResult[] result = super.applyBatch(operations);
283 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700284 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000285 return result;
286 } finally {
287 db.endTransaction();
288 }
289 }
290
291 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700293 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
295
296 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
297 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700298 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299
Sunny Goyald1064182015-08-13 12:08:30 -0700300 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 return count;
302 }
303
304 @Override
305 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700306 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
308
Chris Wren1ada10d2013-09-13 18:01:38 -0400309 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
311 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700312 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313
Sunny Goyald1064182015-08-13 12:08:30 -0700314 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 return count;
316 }
317
Sunny Goyal7779d622015-06-11 16:18:39 -0700318 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700319 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700320 if (Binder.getCallingUid() != Process.myUid()) {
321 return null;
322 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700324
325 switch (method) {
326 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
327 Bundle result = new Bundle();
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800328 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(arg)) {
329 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
330 Utilities.isAllowRotationPrefEnabled(getContext()));
331 } else {
332 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
333 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
334 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
335 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700336 return result;
337 }
338 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
Tony Wickham827cef22016-03-17 15:39:39 -0700339 final boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700340 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyalb171e562016-01-21 16:41:54 -0800341 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
342 LauncherBackupAgentHelper.dataChanged(getContext());
343 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700344 Bundle result = new Bundle();
345 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
346 return result;
347 }
Tony Wickham827cef22016-03-17 15:39:39 -0700348 case LauncherSettings.Settings.METHOD_SET_EXTRACTED_COLORS_AND_WALLPAPER_ID: {
349 String extractedColors = extras.getString(
350 LauncherSettings.Settings.EXTRA_EXTRACTED_COLORS);
351 int wallpaperId = extras.getInt(LauncherSettings.Settings.EXTRA_WALLPAPER_ID);
352 Utilities.getPrefs(getContext()).edit()
353 .putString(ExtractionUtils.EXTRACTED_COLORS_PREFERENCE_KEY, extractedColors)
354 .putInt(ExtractionUtils.WALLPAPER_ID_PREFERENCE_KEY, wallpaperId)
355 .apply();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700356 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_EXTRACTED_COLORS_CHANGED);
Tony Wickham827cef22016-03-17 15:39:39 -0700357 Bundle result = new Bundle();
358 result.putString(LauncherSettings.Settings.EXTRA_VALUE, extractedColors);
359 return result;
360 }
Sunny Goyald2497482015-09-22 18:24:19 -0700361 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
362 clearFlagEmptyDbCreated();
363 return null;
364 }
365 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
366 Bundle result = new Bundle();
367 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
368 return result;
369 }
370 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
371 Bundle result = new Bundle();
372 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
373 return result;
374 }
375 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
376 Bundle result = new Bundle();
377 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
378 return result;
379 }
380 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
381 createEmptyDB();
382 return null;
383 }
384 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
385 loadDefaultFavoritesIfNecessary();
386 return null;
387 }
388 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
389 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
390 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700391 Utilities.getPrefs(getContext()).edit().putBoolean(EMPTY_DATABASE_CREATED, false)
392 .commit();
Sunny Goyald2497482015-09-22 18:24:19 -0700393 return null;
394 }
395 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
396 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
397 return null;
398 }
399 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
400 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
401 return null;
402 }
403 case LauncherSettings.Settings.METHOD_DELETE_DB: {
Sunny Goyalaefc0c42015-12-10 17:46:12 -0800404 // Are you sure? (y/n)
405 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700406 return null;
407 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700408 }
409 return null;
410 }
411
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700412 /**
413 * Deletes any empty folder from the DB.
414 * @return Ids of deleted folders.
415 */
Sunny Goyald2497482015-09-22 18:24:19 -0700416 private ArrayList<Long> deleteEmptyFolders() {
417 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700418 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
419 db.beginTransaction();
420 try {
421 // Select folders whose id do not match any container value.
422 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
423 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
424 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
425 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700426 + Favorites.TABLE_NAME + ")";
427 Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 new String[] {LauncherSettings.Favorites._ID},
429 selection, null, null, null, null);
430 while (c.moveToNext()) {
431 folderIds.add(c.getLong(0));
432 }
433 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700434 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700435 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700436 LauncherSettings.Favorites._ID, folderIds), null);
437 }
438 db.setTransactionSuccessful();
439 } catch (SQLException ex) {
440 Log.e(TAG, ex.getMessage(), ex);
441 folderIds.clear();
442 } finally {
443 db.endTransaction();
444 }
445 return folderIds;
446 }
447
Sunny Goyalf076eae2016-01-11 12:25:10 -0800448 /**
449 * Overridden in tests
450 */
451 protected void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400453 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700454 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400455 }
456
Adam Cohen091440a2015-03-18 14:16:05 -0700457 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400458 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800459 }
460
Brian Muramatsu5524b492012-10-02 16:55:54 -0700461 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700462 * Clears all the data for a fresh start.
463 */
Sunny Goyald2497482015-09-22 18:24:19 -0700464 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700465 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
466 }
467
Sunny Goyald2497482015-09-22 18:24:19 -0700468 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700469 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700470 }
471
Sunny Goyal42de82f2014-09-26 22:09:29 -0700472 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700474 * 1) From the app restrictions
475 * 2) From a package provided by play store
476 * 3) From a partner configuration APK, already in the system image
477 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700478 */
Sunny Goyald2497482015-09-22 18:24:19 -0700479 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700480 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700481
Winson Chungc763c4e2013-07-19 13:49:06 -0700482 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500483 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200484
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700485 AppWidgetHost widgetHost = new AppWidgetHost(getContext(), Launcher.APPWIDGET_HOST_ID);
486 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700487 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700489 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700490 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700491 final Partner partner = Partner.get(getContext().getPackageManager());
492 if (partner != null && partner.hasDefaultLayout()) {
493 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700494 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700495 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700496 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700497 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700498 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700499 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700500 }
501 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502
Sunny Goyal9d219682014-10-23 14:21:02 -0700503 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700504 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700506 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800507
508 // There might be some partially restored DB items, due to buggy restore logic in
509 // previous versions of launcher.
510 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700511 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700512 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
513 && usingExternallyProvidedLayout) {
514 // Unable to load external layout. Cleanup and load the internal layout.
515 createEmptyDB();
516 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700517 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700518 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700519 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700520 }
521 }
522
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700523 /**
524 * Creates workspace loader from an XML resource listed in the app restrictions.
525 *
526 * @return the loader if the restrictions are set and the resource exists; null otherwise.
527 */
528 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700529 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700530 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700531 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700532 return null;
533 }
534
535 Context ctx = getContext();
536 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
537 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700538 if (bundle == null) {
539 return null;
540 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541
Sunny Goyal35ca8732015-04-06 10:45:31 -0700542 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700543 if (packageName != null) {
544 try {
545 Resources targetResources = ctx.getPackageManager()
546 .getResourcesForApplication(packageName);
547 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700549 } catch (NameNotFoundException e) {
550 Log.e(TAG, "Target package for restricted profile not found", e);
551 return null;
552 }
553 }
554 return null;
555 }
556
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700558 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700559 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700560 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700561 mOpenHelper, getContext().getResources(), defaultLayout);
562 }
563
Sunny Goyald3849d12015-10-29 10:28:32 -0700564 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800565 * The class is subclassed in tests to create an in-memory db.
566 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700567 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800569 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 private long mMaxItemId = -1;
571 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700573 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
574 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700575 // Table creation sometimes fails silently, which leads to a crash loop.
576 // This way, we will try to create a table every time after crash, so the device
577 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700578 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700579 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
580 // This operation is a no-op if the table already exists.
581 addFavoritesTable(getWritableDatabase(), true);
582 addWorkspacesTable(getWritableDatabase(), true);
583 }
584
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700585 initIds();
586 }
587
588 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700589 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700590 */
591 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700592 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700593 super(new NoLocaleSqliteContext(context), tableName, null, DATABASE_VERSION);
594 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700595 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700596 }
597
598 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700599 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
600 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700601 if (mMaxItemId == -1) {
602 mMaxItemId = initializeMaxItemId(getWritableDatabase());
603 }
604 if (mMaxScreenId == -1) {
605 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700606 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700609 private boolean tableExists(String tableName) {
610 Cursor c = getReadableDatabase().query(
611 true, "sqlite_master", new String[] {"tbl_name"},
612 "tbl_name = ?", new String[] {tableName},
613 null, null, null, null, null);
614 try {
615 return c.getCount() > 0;
616 } finally {
617 c.close();
618 }
619 }
620
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 @Override
622 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800623 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700624
Adam Cohendcd297f2013-06-18 13:13:40 -0700625 mMaxItemId = 1;
626 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700627
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700628 addFavoritesTable(db, false);
629 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800631 // Fresh and clean launcher DB.
632 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 onEmptyDbCreated();
634 }
635
636 /**
637 * Overriden in tests.
638 */
639 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700640 // Database was just created, so wipe any previous widgets
641 if (mWidgetHostResetHandler != null) {
642 new AppWidgetHost(mContext, Launcher.APPWIDGET_HOST_ID).deleteHost();
643 mWidgetHostResetHandler.sendEmptyMessage(
644 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
645 }
646
Sunny Goyalf076eae2016-01-11 12:25:10 -0800647 // Set the flag for empty DB
648 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700649
650 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyalf076eae2016-01-11 12:25:10 -0800651 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(),
652 mContext);
653 }
654
655 protected long getDefaultUserSerial() {
656 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
657 UserHandleCompat.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 }
659
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700660 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700661 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700662 }
663
664 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
665 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700666 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800667 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400668 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
669 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700670 ");");
671 }
672
Adam Cohen119285e2014-04-02 16:59:08 -0700673 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700674 // Delete items directly on the workspace who's screen id doesn't exist
675 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
676 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700677 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700678 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700679 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700680 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700681 " AND " +
682 LauncherSettings.Favorites.CONTAINER + " = " +
683 LauncherSettings.Favorites.CONTAINER_DESKTOP;
684 db.execSQL(removeOrphanedDesktopItems);
685
686 // Delete items contained in folders which no longer exist (after above statement)
687 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
688 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700689 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700690 " WHERE " +
691 LauncherSettings.Favorites.CONTAINER + " <> " +
692 LauncherSettings.Favorites.CONTAINER_DESKTOP +
693 " AND "
694 + LauncherSettings.Favorites.CONTAINER + " <> " +
695 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
696 " AND "
697 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700698 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700699 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
700 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
701 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700702 }
703
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800704 @Override
705 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700706 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800707 switch (oldVersion) {
708 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800709 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800710 case 12: {
711 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
712 // to persist workspace screens and their relative order.
713 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700714 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800715 }
716 case 13: {
717 db.beginTransaction();
718 try {
719 // Insert new column for holding widget provider name
720 db.execSQL("ALTER TABLE favorites " +
721 "ADD COLUMN appWidgetProvider TEXT;");
722 db.setTransactionSuccessful();
723 } catch (SQLException ex) {
724 Log.e(TAG, ex.getMessage(), ex);
725 // Old version remains, which means we wipe old data
726 break;
727 } finally {
728 db.endTransaction();
729 }
730 }
731 case 14: {
732 db.beginTransaction();
733 try {
734 // Insert new column for holding update timestamp
735 db.execSQL("ALTER TABLE favorites " +
736 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
737 db.execSQL("ALTER TABLE workspaceScreens " +
738 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
739 db.setTransactionSuccessful();
740 } catch (SQLException ex) {
741 Log.e(TAG, ex.getMessage(), ex);
742 // Old version remains, which means we wipe old data
743 break;
744 } finally {
745 db.endTransaction();
746 }
747 }
748 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700749 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800750 // Old version remains, which means we wipe old data
751 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800752 }
753 }
754 case 16: {
755 // We use the db version upgrade here to identify users who may not have seen
756 // clings yet (because they weren't available), but for whom the clings are now
757 // available (tablet users). Because one of the possible cling flows (migration)
758 // is very destructive (wipes out workspaces), we want to prevent this from showing
759 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800760 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 }
762 case 17: {
763 // No-op
764 }
765 case 18: {
766 // Due to a data loss bug, some users may have items associated with screen ids
767 // which no longer exist. Since this can cause other problems, and since the user
768 // will never see these items anyway, we use database upgrade as an opportunity to
769 // clean things up.
770 removeOrphanedItems(db);
771 }
772 case 19: {
773 // Add userId column
774 if (!addProfileColumn(db)) {
775 // Old version remains, which means we wipe old data
776 break;
777 }
778 }
779 case 20:
780 if (!updateFolderItemsRank(db, true)) {
781 break;
782 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800783 case 21:
784 // Recreate workspace table with screen id a primary key
785 if (!recreateWorkspaceTable(db)) {
786 break;
787 }
788 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700789 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
790 // Old version remains, which means we wipe old data
791 break;
792 }
793 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700794 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700795 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700796 case 24:
797 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700798 case 25:
799 convertShortcutsToLauncherActivities(db);
800 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800801 // DB Upgraded successfully
802 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400803 }
804 }
805
Sunny Goyala2cc6242015-01-14 14:23:02 -0800806 // DB was not upgraded
807 Log.w(TAG, "Destroying all old data.");
808 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800809 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800810
Adam Cohen9b1d0622014-05-21 19:01:57 -0700811 @Override
812 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
813 // This shouldn't happen -- throw our hands up in the air and start over.
814 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
815 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700816 createEmptyDB(db);
817 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700818
Sunny Goyal42de82f2014-09-26 22:09:29 -0700819 /**
820 * Clears all the data for a fresh start.
821 */
822 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700823 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
824 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Adam Cohen9b1d0622014-05-21 19:01:57 -0700825 onCreate(db);
826 }
827
Sunny Goyald2f38192015-02-25 10:46:34 -0800828 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700829 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
830 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
831 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700832 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700833 db.beginTransaction();
834 Cursor c = null;
835 SQLiteStatement updateStmt = null;
836
837 try {
838 // Only consider the primary user as other users can't have a shortcut.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700839 long userSerial = getDefaultUserSerial();
840 c = db.query(Favorites.TABLE_NAME, new String[] {
Sunny Goyal0b037782015-04-02 10:27:03 -0700841 Favorites._ID,
842 Favorites.INTENT,
843 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
844 null, null, null, null);
845
846 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
847 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
848
849 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
850 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
851
852 while (c.moveToNext()) {
853 String intentDescription = c.getString(intentIndex);
854 Intent intent;
855 try {
856 intent = Intent.parseUri(intentDescription, 0);
857 } catch (URISyntaxException e) {
858 Log.e(TAG, "Unable to parse intent", e);
859 continue;
860 }
861
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700862 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700863 continue;
864 }
865
866 long id = c.getLong(idIndex);
867 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700868 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700869 }
870 db.setTransactionSuccessful();
871 } catch (SQLException ex) {
872 Log.w(TAG, "Error deduping shortcuts", ex);
873 } finally {
874 db.endTransaction();
875 if (c != null) {
876 c.close();
877 }
878 if (updateStmt != null) {
879 updateStmt.close();
880 }
881 }
882 }
883
884 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800885 * Recreates workspace table and migrates data to the new table.
886 */
887 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
888 db.beginTransaction();
889 try {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700890 Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800891 new String[] {LauncherSettings.WorkspaceScreens._ID},
892 null, null, null, null,
893 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
894 ArrayList<Long> sortedIDs = new ArrayList<Long>();
895 long maxId = 0;
896 try {
897 while (c.moveToNext()) {
898 Long id = c.getLong(0);
899 if (!sortedIDs.contains(id)) {
900 sortedIDs.add(id);
901 maxId = Math.max(maxId, id);
902 }
903 }
904 } finally {
905 c.close();
906 }
907
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700908 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700909 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800910
911 // Add all screen ids back
912 int total = sortedIDs.size();
913 for (int i = 0; i < total; i++) {
914 ContentValues values = new ContentValues();
915 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
916 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
917 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700918 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800919 }
920 db.setTransactionSuccessful();
921 mMaxScreenId = maxId;
922 } catch (SQLException ex) {
923 // Old version remains, which means we wipe old data
924 Log.e(TAG, ex.getMessage(), ex);
925 return false;
926 } finally {
927 db.endTransaction();
928 }
929 return true;
930 }
931
Adam Cohen091440a2015-03-18 14:16:05 -0700932 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800933 db.beginTransaction();
934 try {
935 if (addRankColumn) {
936 // Insert new column for holding rank
937 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
938 }
939
940 // Get a map for folder ID to folder width
941 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
942 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
943 + " GROUP BY container;",
944 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
945
946 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800947 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
948 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800949 new Object[] {c.getLong(1) + 1, c.getLong(0)});
950 }
951
952 c.close();
953 db.setTransactionSuccessful();
954 } catch (SQLException ex) {
955 // Old version remains, which means we wipe old data
956 Log.e(TAG, ex.getMessage(), ex);
957 return false;
958 } finally {
959 db.endTransaction();
960 }
961 return true;
962 }
963
Kenny Guyed131872014-04-30 03:02:21 +0100964 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700965 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700966 }
967
968 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100969 db.beginTransaction();
970 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700971 db.execSQL("ALTER TABLE favorites ADD COLUMN "
972 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100973 db.setTransactionSuccessful();
974 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100975 Log.e(TAG, ex.getMessage(), ex);
976 return false;
977 } finally {
978 db.endTransaction();
979 }
980 return true;
981 }
982
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700983 // Generates a new ID to use for an object in your database. This method should be only
984 // called from the main UI thread. As an exception, we do call it when we call the
985 // constructor from the worker thread; however, this doesn't extend until after the
986 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
987 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700988 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700989 public long generateNewItemId() {
990 if (mMaxItemId < 0) {
991 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700992 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 mMaxItemId += 1;
994 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700995 }
996
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700997 @Override
998 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700999 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001000 }
1001
Chris Wren5dee7af2013-12-20 17:22:11 -05001002 public void checkId(String table, ContentValues values) {
1003 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001004 if (table == WorkspaceScreens.TABLE_NAME) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001005 mMaxScreenId = Math.max(id, mMaxScreenId);
1006 } else {
1007 mMaxItemId = Math.max(id, mMaxItemId);
1008 }
1009 }
1010
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001012 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001013 }
1014
1015 // Generates a new ID to use for an workspace screen in your database. This method
1016 // should be only called from the main UI thread. As an exception, we do call it when we
1017 // call the constructor from the worker thread; however, this doesn't extend until after the
1018 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1019 // after that point
1020 public long generateNewScreenId() {
1021 if (mMaxScreenId < 0) {
1022 throw new RuntimeException("Error: max screen id was not initialized");
1023 }
1024 mMaxScreenId += 1;
1025 return mMaxScreenId;
1026 }
1027
Adam Cohendcd297f2013-06-18 13:13:40 -07001028 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001029 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001030 }
1031
Adam Cohen091440a2015-03-18 14:16:05 -07001032 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001033 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001034 // TODO: Use multiple loaders with fall-back and transaction.
1035 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001036
1037 // Add the screens specified by the items above
1038 Collections.sort(screenIds);
1039 int rank = 0;
1040 ContentValues values = new ContentValues();
1041 for (Long id : screenIds) {
1042 values.clear();
1043 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1044 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001045 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001046 throw new RuntimeException("Failed initialize screen table"
1047 + "from default layout");
1048 }
1049 rank++;
1050 }
1051
1052 // Ensure that the max ids are initialized
1053 mMaxItemId = initializeMaxItemId(db);
1054 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001055
Adam Cohen71483f42014-05-15 14:04:01 -07001056 return count;
1057 }
1058
Adam Cohen091440a2015-03-18 14:16:05 -07001059 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001060 final ContentResolver resolver = mContext.getContentResolver();
1061 Cursor c = null;
1062 int count = 0;
1063 int curScreen = 0;
1064
1065 try {
1066 c = resolver.query(uri, null, null, null, "title ASC");
1067 } catch (Exception e) {
1068 // Ignore
1069 }
1070
Dan Sandlerd5024042014-01-09 15:01:33 -05001071 // We already have a favorites database in the old provider
1072 if (c != null) {
1073 try {
1074 if (c.getCount() > 0) {
1075 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1076 final int intentIndex
1077 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1078 final int titleIndex
1079 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1080 final int iconTypeIndex
1081 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1082 final int iconIndex
1083 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1084 final int iconPackageIndex
1085 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1086 final int iconResourceIndex
1087 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1088 final int containerIndex
1089 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1090 final int itemTypeIndex
1091 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1092 final int screenIndex
1093 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1094 final int cellXIndex
1095 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1096 final int cellYIndex
1097 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001098 final int profileIndex
1099 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001100
1101 int i = 0;
1102 int curX = 0;
1103 int curY = 0;
1104
1105 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001106 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1107 final int width = (int) profile.numColumns;
1108 final int height = (int) profile.numRows;
1109 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001110
1111 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1112
Adam Cohen72960972014-01-15 18:13:55 -08001113 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1114 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001115 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001116
1117 while (c.moveToNext()) {
1118 final int itemType = c.getInt(itemTypeIndex);
1119 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1120 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1121 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1122 continue;
1123 }
1124
1125 final int cellX = c.getInt(cellXIndex);
1126 final int cellY = c.getInt(cellYIndex);
1127 final int screen = c.getInt(screenIndex);
1128 int container = c.getInt(containerIndex);
1129 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001130
1131 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1132 UserHandleCompat userHandle;
1133 final long userSerialNumber;
1134 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1135 userSerialNumber = c.getInt(profileIndex);
1136 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1137 } else {
1138 // Default to the serial number of this user, for older
1139 // shortcuts.
1140 userHandle = UserHandleCompat.myUserHandle();
1141 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1142 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001143
1144 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001145 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001146 continue;
1147 }
1148
Dan Sandlerd5024042014-01-09 15:01:33 -05001149 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001150
1151 final Intent intent;
1152 final ComponentName cn;
1153 try {
1154 intent = Intent.parseUri(intentStr, 0);
1155 } catch (URISyntaxException e) {
1156 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001157 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001158 continue;
1159 }
1160
1161 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001162 if (TextUtils.isEmpty(intentStr)) {
1163 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001164 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001165 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001166 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001167 !LauncherModel.isValidPackageActivity(mContext, cn,
1168 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001169 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001170 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001171 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001172 } else if (container ==
1173 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1174 // Dedupe icons directly on the workspace
1175
Adam Cohen556f6132014-01-15 15:18:08 -08001176 // Canonicalize
1177 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001178 // does not, so we clear that out to keep them the same.
1179 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001180 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001181 int flags = intent.getFlags();
1182 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001183 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001184 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001185 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001186 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001187 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001188 } else {
1189 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001190 }
1191 }
1192 }
1193
1194 ContentValues values = new ContentValues(c.getColumnCount());
1195 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1196 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1197 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1198 values.put(LauncherSettings.Favorites.ICON_TYPE,
1199 c.getInt(iconTypeIndex));
1200 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1201 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1202 c.getString(iconPackageIndex));
1203 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1204 c.getString(iconResourceIndex));
1205 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1206 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001207 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001208
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001209 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1210 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001211 }
1212
1213 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1214 // In a folder or in the hotseat, preserve position
1215 values.put(LauncherSettings.Favorites.SCREEN, screen);
1216 values.put(LauncherSettings.Favorites.CELLX, cellX);
1217 values.put(LauncherSettings.Favorites.CELLY, cellY);
1218 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001219 // For items contained directly on one of the workspace screen,
1220 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001221 }
1222
1223 values.put(LauncherSettings.Favorites.CONTAINER, container);
1224
Adam Cohen72960972014-01-15 18:13:55 -08001225 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1226 shortcuts.add(values);
1227 } else {
1228 folders.add(values);
1229 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001230 }
1231
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001232 // Now that we have all the hotseat icons, let's go through them left-right
1233 // and assign valid locations for them in the new hotseat
1234 final int N = hotseat.size();
1235 for (int idx=0; idx<N; idx++) {
1236 int hotseatX = hotseat.keyAt(idx);
1237 ContentValues values = hotseat.valueAt(idx);
1238
Adam Cohen2e6da152015-05-06 11:42:25 -07001239 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001240 // let's drop this in the next available hole in the hotseat
1241 while (++hotseatX < hotseatWidth) {
1242 if (hotseat.get(hotseatX) == null) {
1243 // found a spot! move it here
1244 values.put(LauncherSettings.Favorites.SCREEN,
1245 hotseatX);
1246 break;
1247 }
1248 }
1249 }
1250 if (hotseatX >= hotseatWidth) {
1251 // no room for you in the hotseat? it's off to the desktop with you
1252 values.put(LauncherSettings.Favorites.CONTAINER,
1253 Favorites.CONTAINER_DESKTOP);
1254 }
1255 }
1256
Adam Cohen72960972014-01-15 18:13:55 -08001257 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1258 // Folders first
1259 allItems.addAll(folders);
1260 // Then shortcuts
1261 allItems.addAll(shortcuts);
1262
1263 // Layout all the folders
1264 for (ContentValues values: allItems) {
1265 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1266 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1267 // Hotseat items and folder items have already had their
1268 // location information set. Nothing to be done here.
1269 continue;
1270 }
1271 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1272 values.put(LauncherSettings.Favorites.CELLX, curX);
1273 values.put(LauncherSettings.Favorites.CELLY, curY);
1274 curX = (curX + 1) % width;
1275 if (curX == 0) {
1276 curY = (curY + 1);
1277 }
1278 // Leave the last row of icons blank on every screen
1279 if (curY == height - 1) {
1280 curScreen = (int) generateNewScreenId();
1281 curY = 0;
1282 }
1283 }
1284
1285 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001286 db.beginTransaction();
1287 try {
Adam Cohen72960972014-01-15 18:13:55 -08001288 for (ContentValues row: allItems) {
1289 if (row == null) continue;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001290 if (dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001291 < 0) {
1292 return;
1293 } else {
1294 count++;
1295 }
1296 }
1297 db.setTransactionSuccessful();
1298 } finally {
1299 db.endTransaction();
1300 }
1301 }
1302
1303 db.beginTransaction();
1304 try {
1305 for (i=0; i<=curScreen; i++) {
1306 final ContentValues values = new ContentValues();
1307 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1308 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001309 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values)
Dan Sandlerd5024042014-01-09 15:01:33 -05001310 < 0) {
1311 return;
1312 }
1313 }
1314 db.setTransactionSuccessful();
1315 } finally {
1316 db.endTransaction();
1317 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001318
1319 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001320 }
1321 } finally {
1322 c.close();
1323 }
1324 }
1325
Sunny Goyala1365452015-10-01 15:46:24 -07001326 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1327 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001328
Dan Sandlerd5024042014-01-09 15:01:33 -05001329 // Update max IDs; very important since we just grabbed IDs from another database
1330 mMaxItemId = initializeMaxItemId(db);
1331 mMaxScreenId = initializeMaxScreenId(db);
1332 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1333 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001334 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001335
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001336 /**
1337 * @return the max _id in the provided table.
1338 */
Adam Cohen091440a2015-03-18 14:16:05 -07001339 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001340 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1341 // get the result
1342 long id = -1;
1343 if (c != null && c.moveToNext()) {
1344 id = c.getLong(0);
1345 }
1346 if (c != null) {
1347 c.close();
1348 }
1349
1350 if (id == -1) {
1351 throw new RuntimeException("Error: could not query max id in " + table);
1352 }
1353
1354 return id;
1355 }
1356
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001357 static class SqlArguments {
1358 public final String table;
1359 public final String where;
1360 public final String[] args;
1361
1362 SqlArguments(Uri url, String where, String[] args) {
1363 if (url.getPathSegments().size() == 1) {
1364 this.table = url.getPathSegments().get(0);
1365 this.where = where;
1366 this.args = args;
1367 } else if (url.getPathSegments().size() != 2) {
1368 throw new IllegalArgumentException("Invalid URI: " + url);
1369 } else if (!TextUtils.isEmpty(where)) {
1370 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1371 } else {
1372 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001373 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001374 this.args = null;
1375 }
1376 }
1377
1378 SqlArguments(Uri url) {
1379 if (url.getPathSegments().size() == 1) {
1380 table = url.getPathSegments().get(0);
1381 where = null;
1382 args = null;
1383 } else {
1384 throw new IllegalArgumentException("Invalid URI: " + url);
1385 }
1386 }
1387 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001388
1389 private static class ChangeListenerWrapper implements Handler.Callback {
1390
1391 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
1392 private static final int MSG_EXTRACTED_COLORS_CHANGED = 2;
1393 private static final int MSG_APP_WIDGET_HOST_RESET = 3;
1394
1395 private LauncherProviderChangeListener mListener;
1396
1397 @Override
1398 public boolean handleMessage(Message msg) {
1399 if (mListener != null) {
1400 switch (msg.what) {
1401 case MSG_LAUNCHER_PROVIDER_CHANGED:
1402 mListener.onLauncherProviderChange();
1403 break;
1404 case MSG_EXTRACTED_COLORS_CHANGED:
1405 mListener.onExtractedColorsChanged();
1406 break;
1407 case MSG_APP_WIDGET_HOST_RESET:
1408 mListener.onAppWidgetHostReset();
1409 break;
1410 }
1411 }
1412 return true;
1413 }
1414 }
Adam Cohen72960972014-01-15 18:13:55 -08001415}