blob: 17e282048c376fc250e2d782cbb157a6fe82c75e [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080046import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050050import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070067 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Sunny Goyale5bb7052015-07-27 14:36:07 -070072 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070073
Sunny Goyal18b640c2015-04-17 09:24:01 -070074 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
75 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080076 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Sunny Goyal383c5072015-06-12 21:18:53 -070080 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070081 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
83 @Override
84 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040085 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080086 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040087 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080088 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040089 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090 return true;
91 }
92
Anjali Koppal67e7cae2014-03-13 12:14:12 -070093 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
94 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -070095 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -070096 }
97
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 @Override
99 public String getType(Uri uri) {
100 SqlArguments args = new SqlArguments(uri, null, null);
101 if (TextUtils.isEmpty(args.where)) {
102 return "vnd.android.cursor.dir/" + args.table;
103 } else {
104 return "vnd.android.cursor.item/" + args.table;
105 }
106 }
107
108 @Override
109 public Cursor query(Uri uri, String[] projection, String selection,
110 String[] selectionArgs, String sortOrder) {
111
112 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
113 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
114 qb.setTables(args.table);
115
Romain Guy73b979d2009-06-09 12:57:21 -0700116 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800117 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
118 result.setNotificationUri(getContext().getContentResolver(), uri);
119
120 return result;
121 }
122
Adam Cohen091440a2015-03-18 14:16:05 -0700123 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700124 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500125 if (values == null) {
126 throw new RuntimeException("Error: attempting to insert null values");
127 }
Adam Cohen71483f42014-05-15 14:04:01 -0700128 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 throw new RuntimeException("Error: attempting to add item without specifying an id");
130 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500131 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700132 return db.insert(table, nullColumnHack, values);
133 }
134
Sunny Goyald1064182015-08-13 12:08:30 -0700135 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700136 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700137 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
138 if (app != null) {
139 app.reloadWorkspace();
140 }
141 }
142 }
143
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800144 @Override
145 public Uri insert(Uri uri, ContentValues initialValues) {
146 SqlArguments args = new SqlArguments(uri);
147
Sunny Goyald1064182015-08-13 12:08:30 -0700148 // In very limited cases, we support system|signature permission apps to modify the db.
149 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700150 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
151 return null;
152 }
153 }
154
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400156 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800158 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159
160 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700161 notifyListeners();
162
Sunny Goyalc74e4192015-09-08 14:01:03 -0700163 if (Utilities.ATLEAST_MARSHMALLOW) {
164 reloadLauncherIfExternal();
165 } else {
166 // Deprecated behavior to support legacy devices which rely on provider callbacks.
167 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
168 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
169 app.reloadWorkspace();
170 }
171
172 String notify = uri.getQueryParameter("notify");
173 if (notify == null || "true".equals(notify)) {
174 getContext().getContentResolver().notifyChange(uri, null);
175 }
176 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177 return uri;
178 }
179
Adam Cohena043fa82014-07-23 14:49:38 -0700180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 @Override
182 public int bulkInsert(Uri uri, ContentValues[] values) {
183 SqlArguments args = new SqlArguments(uri);
184
185 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
186 db.beginTransaction();
187 try {
188 int numValues = values.length;
189 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400190 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700191 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
192 return 0;
193 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 }
195 db.setTransactionSuccessful();
196 } finally {
197 db.endTransaction();
198 }
199
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700200 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700201 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 return values.length;
203 }
204
205 @Override
Yura085c8532014-02-11 15:15:29 +0000206 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
207 throws OperationApplicationException {
208 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
209 db.beginTransaction();
210 try {
211 ContentProviderResult[] result = super.applyBatch(operations);
212 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700213 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000214 return result;
215 } finally {
216 db.endTransaction();
217 }
218 }
219
220 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 public int delete(Uri uri, String selection, String[] selectionArgs) {
222 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
223
224 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
225 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700226 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227
Sunny Goyald1064182015-08-13 12:08:30 -0700228 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 return count;
230 }
231
232 @Override
233 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
234 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
235
Chris Wren1ada10d2013-09-13 18:01:38 -0400236 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
238 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700239 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240
Sunny Goyald1064182015-08-13 12:08:30 -0700241 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return count;
243 }
244
Sunny Goyal7779d622015-06-11 16:18:39 -0700245 @Override
246 public Bundle call(String method, String arg, Bundle extras) {
247 if (Binder.getCallingUid() != Process.myUid()) {
248 return null;
249 }
250
251 switch (method) {
252 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
253 Bundle result = new Bundle();
254 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700255 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
256 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700257 return result;
258 }
259 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
260 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700261 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyal7779d622015-06-11 16:18:39 -0700262 if (mListener != null) {
263 mListener.onSettingsChanged(arg, value);
264 }
265 Bundle result = new Bundle();
266 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
267 return result;
268 }
Sunny Goyald2497482015-09-22 18:24:19 -0700269 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
270 clearFlagEmptyDbCreated();
271 return null;
272 }
273 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
274 Bundle result = new Bundle();
275 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
276 return result;
277 }
278 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
279 Bundle result = new Bundle();
280 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
281 return result;
282 }
283 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
284 Bundle result = new Bundle();
285 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
286 return result;
287 }
288 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
289 createEmptyDB();
290 return null;
291 }
292 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
293 loadDefaultFavoritesIfNecessary();
294 return null;
295 }
296 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
297 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
298 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
299 return null;
300 }
301 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
302 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
303 return null;
304 }
305 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
306 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
307 return null;
308 }
309 case LauncherSettings.Settings.METHOD_DELETE_DB: {
310 deleteDatabase();
311 return null;
312 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700313 }
314 return null;
315 }
316
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700317 /**
318 * Deletes any empty folder from the DB.
319 * @return Ids of deleted folders.
320 */
Sunny Goyald2497482015-09-22 18:24:19 -0700321 private ArrayList<Long> deleteEmptyFolders() {
322 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700323 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
324 db.beginTransaction();
325 try {
326 // Select folders whose id do not match any container value.
327 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
328 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
329 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
330 LauncherSettings.Favorites.CONTAINER + " FROM "
331 + TABLE_FAVORITES + ")";
332 Cursor c = db.query(TABLE_FAVORITES,
333 new String[] {LauncherSettings.Favorites._ID},
334 selection, null, null, null, null);
335 while (c.moveToNext()) {
336 folderIds.add(c.getLong(0));
337 }
338 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700339 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700340 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
341 LauncherSettings.Favorites._ID, folderIds), null);
342 }
343 db.setTransactionSuccessful();
344 } catch (SQLException ex) {
345 Log.e(TAG, ex.getMessage(), ex);
346 folderIds.clear();
347 } finally {
348 db.endTransaction();
349 }
350 return folderIds;
351 }
352
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700353 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400354 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400355 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700356 if (mListener != null) {
357 mListener.onLauncherProviderChange();
358 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400359 }
360
Adam Cohen091440a2015-03-18 14:16:05 -0700361 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400362 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800363 }
364
Brian Muramatsu5524b492012-10-02 16:55:54 -0700365 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700366 * Clears all the data for a fresh start.
367 */
Sunny Goyald2497482015-09-22 18:24:19 -0700368 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700369 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
370 }
371
Sunny Goyald2497482015-09-22 18:24:19 -0700372 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700373 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700374 }
375
Sunny Goyal42de82f2014-09-26 22:09:29 -0700376 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700377 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700378 * 1) From the app restrictions
379 * 2) From a package provided by play store
380 * 3) From a partner configuration APK, already in the system image
381 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700382 */
Sunny Goyald2497482015-09-22 18:24:19 -0700383 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700384 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700385
Winson Chungc763c4e2013-07-19 13:49:06 -0700386 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500387 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200388
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700389 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
390 if (loader == null) {
391 loader = AutoInstallsLayout.get(getContext(),
392 mOpenHelper.mAppWidgetHost, mOpenHelper);
393 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700394 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700395 final Partner partner = Partner.get(getContext().getPackageManager());
396 if (partner != null && partner.hasDefaultLayout()) {
397 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700398 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700399 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700400 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700401 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
402 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700403 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700404 }
405 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700406
Sunny Goyal9d219682014-10-23 14:21:02 -0700407 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700408 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700409 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700410 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800411
412 // There might be some partially restored DB items, due to buggy restore logic in
413 // previous versions of launcher.
414 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700415 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700416 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
417 && usingExternallyProvidedLayout) {
418 // Unable to load external layout. Cleanup and load the internal layout.
419 createEmptyDB();
420 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
421 getDefaultLayoutParser());
422 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700423 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700424 }
425 }
426
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700427 /**
428 * Creates workspace loader from an XML resource listed in the app restrictions.
429 *
430 * @return the loader if the restrictions are set and the resource exists; null otherwise.
431 */
432 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
433 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
434 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700435 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700436 return null;
437 }
438
439 Context ctx = getContext();
440 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
441 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700442 if (bundle == null) {
443 return null;
444 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700445
Sunny Goyal35ca8732015-04-06 10:45:31 -0700446 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700447 if (packageName != null) {
448 try {
449 Resources targetResources = ctx.getPackageManager()
450 .getResourcesForApplication(packageName);
451 return AutoInstallsLayout.get(ctx, packageName, targetResources,
452 mOpenHelper.mAppWidgetHost, mOpenHelper);
453 } catch (NameNotFoundException e) {
454 Log.e(TAG, "Target package for restricted profile not found", e);
455 return null;
456 }
457 }
458 return null;
459 }
460
Sunny Goyal9d219682014-10-23 14:21:02 -0700461 private DefaultLayoutParser getDefaultLayoutParser() {
462 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700463 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700464 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
465 mOpenHelper, getContext().getResources(), defaultLayout);
466 }
467
Sunny Goyald2497482015-09-22 18:24:19 -0700468 private void deleteDatabase() {
Dan Sandlerd5024042014-01-09 15:01:33 -0500469 // Are you sure? (y/n)
470 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500471 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500472 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500473 if (dbFile.exists()) {
474 SQLiteDatabase.deleteDatabase(dbFile);
475 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500476 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700477 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500478 }
479
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800481 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700482 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700483 private long mMaxItemId = -1;
484 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800485
Winson Chung0b560dd2014-01-21 13:00:26 -0800486 private boolean mNewDbCreated = false;
487
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700488 @Thunk LauncherProviderChangeListener mListener;
489
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800490 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100491 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700493 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700494
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700495 // Table creation sometimes fails silently, which leads to a crash loop.
496 // This way, we will try to create a table every time after crash, so the device
497 // would eventually be able to recover.
498 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
499 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
500 // This operation is a no-op if the table already exists.
501 addFavoritesTable(getWritableDatabase(), true);
502 addWorkspacesTable(getWritableDatabase(), true);
503 }
504
Winson Chung3d503fb2011-07-13 17:25:49 -0700505 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
506 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700507 if (mMaxItemId == -1) {
508 mMaxItemId = initializeMaxItemId(getWritableDatabase());
509 }
510 if (mMaxScreenId == -1) {
511 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700512 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800513 }
514
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700515 private boolean tableExists(String tableName) {
516 Cursor c = getReadableDatabase().query(
517 true, "sqlite_master", new String[] {"tbl_name"},
518 "tbl_name = ?", new String[] {tableName},
519 null, null, null, null, null);
520 try {
521 return c.getCount() > 0;
522 } finally {
523 c.close();
524 }
525 }
526
Winson Chung0b560dd2014-01-21 13:00:26 -0800527 public boolean wasNewDbCreated() {
528 return mNewDbCreated;
529 }
530
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800531 @Override
532 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800533 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700534
Adam Cohendcd297f2013-06-18 13:13:40 -0700535 mMaxItemId = 1;
536 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800537 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700538
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700539 addFavoritesTable(db, false);
540 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800541
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700542 // Database was just created, so wipe any previous widgets
543 if (mAppWidgetHost != null) {
544 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700545
546 /**
547 * Send notification that we've deleted the {@link AppWidgetHost},
548 * probably as part of the initial database creation. The receiver may
549 * want to re-call {@link AppWidgetHost#startListening()} to ensure
550 * callbacks are correctly set.
551 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700552 new MainThreadExecutor().execute(new Runnable() {
553
554 @Override
555 public void run() {
556 if (mListener != null) {
557 mListener.onAppWidgetHostReset();
558 }
559 }
560 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700562
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800563 // Fresh and clean launcher DB.
564 mMaxItemId = initializeMaxItemId(db);
565 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700566
567 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700568 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800569 }
570
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700571 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
572 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
573 long userSerialNumber = userManager.getSerialNumberForUser(
574 UserHandleCompat.myUserHandle());
575 String ifNotExists = optional ? " IF NOT EXISTS " : "";
576
577 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
578 "_id INTEGER PRIMARY KEY," +
579 "title TEXT," +
580 "intent TEXT," +
581 "container INTEGER," +
582 "screen INTEGER," +
583 "cellX INTEGER," +
584 "cellY INTEGER," +
585 "spanX INTEGER," +
586 "spanY INTEGER," +
587 "itemType INTEGER," +
588 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
589 "isShortcut INTEGER," +
590 "iconType INTEGER," +
591 "iconPackage TEXT," +
592 "iconResource TEXT," +
593 "icon BLOB," +
594 "uri TEXT," +
595 "displayMode INTEGER," +
596 "appWidgetProvider TEXT," +
597 "modified INTEGER NOT NULL DEFAULT 0," +
598 "restored INTEGER NOT NULL DEFAULT 0," +
599 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
600 "rank INTEGER NOT NULL DEFAULT 0," +
601 "options INTEGER NOT NULL DEFAULT 0" +
602 ");");
603 }
604
605 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
606 String ifNotExists = optional ? " IF NOT EXISTS " : "";
607 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800608 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400609 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
610 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700611 ");");
612 }
613
Adam Cohen119285e2014-04-02 16:59:08 -0700614 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700615 // Delete items directly on the workspace who's screen id doesn't exist
616 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
617 // AND container = -100"
618 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
619 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700620 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700621 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
622 " AND " +
623 LauncherSettings.Favorites.CONTAINER + " = " +
624 LauncherSettings.Favorites.CONTAINER_DESKTOP;
625 db.execSQL(removeOrphanedDesktopItems);
626
627 // Delete items contained in folders which no longer exist (after above statement)
628 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
629 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
630 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
631 " WHERE " +
632 LauncherSettings.Favorites.CONTAINER + " <> " +
633 LauncherSettings.Favorites.CONTAINER_DESKTOP +
634 " AND "
635 + LauncherSettings.Favorites.CONTAINER + " <> " +
636 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
637 " AND "
638 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
639 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
640 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
641 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
642 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700643 }
644
Winson Chungc763c4e2013-07-19 13:49:06 -0700645 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700646 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700647 }
648
Winson Chungc763c4e2013-07-19 13:49:06 -0700649 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700650 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700651 }
652
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653 @Override
654 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700655 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800656 switch (oldVersion) {
657 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800658 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 case 12: {
660 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
661 // to persist workspace screens and their relative order.
662 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700663 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800664 }
665 case 13: {
666 db.beginTransaction();
667 try {
668 // Insert new column for holding widget provider name
669 db.execSQL("ALTER TABLE favorites " +
670 "ADD COLUMN appWidgetProvider TEXT;");
671 db.setTransactionSuccessful();
672 } catch (SQLException ex) {
673 Log.e(TAG, ex.getMessage(), ex);
674 // Old version remains, which means we wipe old data
675 break;
676 } finally {
677 db.endTransaction();
678 }
679 }
680 case 14: {
681 db.beginTransaction();
682 try {
683 // Insert new column for holding update timestamp
684 db.execSQL("ALTER TABLE favorites " +
685 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
686 db.execSQL("ALTER TABLE workspaceScreens " +
687 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
688 db.setTransactionSuccessful();
689 } catch (SQLException ex) {
690 Log.e(TAG, ex.getMessage(), ex);
691 // Old version remains, which means we wipe old data
692 break;
693 } finally {
694 db.endTransaction();
695 }
696 }
697 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700698 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800699 // Old version remains, which means we wipe old data
700 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800701 }
702 }
703 case 16: {
704 // We use the db version upgrade here to identify users who may not have seen
705 // clings yet (because they weren't available), but for whom the clings are now
706 // available (tablet users). Because one of the possible cling flows (migration)
707 // is very destructive (wipes out workspaces), we want to prevent this from showing
708 // until clear data. We do so by marking that the clings have been shown.
709 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
710 }
711 case 17: {
712 // No-op
713 }
714 case 18: {
715 // Due to a data loss bug, some users may have items associated with screen ids
716 // which no longer exist. Since this can cause other problems, and since the user
717 // will never see these items anyway, we use database upgrade as an opportunity to
718 // clean things up.
719 removeOrphanedItems(db);
720 }
721 case 19: {
722 // Add userId column
723 if (!addProfileColumn(db)) {
724 // Old version remains, which means we wipe old data
725 break;
726 }
727 }
728 case 20:
729 if (!updateFolderItemsRank(db, true)) {
730 break;
731 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800732 case 21:
733 // Recreate workspace table with screen id a primary key
734 if (!recreateWorkspaceTable(db)) {
735 break;
736 }
737 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700738 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
739 // Old version remains, which means we wipe old data
740 break;
741 }
742 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700743 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700744 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700745 case 24:
746 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700747 case 25:
748 convertShortcutsToLauncherActivities(db);
749 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800750 // DB Upgraded successfully
751 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400752 }
753 }
754
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 // DB was not upgraded
756 Log.w(TAG, "Destroying all old data.");
757 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800758 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800759
Adam Cohen9b1d0622014-05-21 19:01:57 -0700760 @Override
761 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
762 // This shouldn't happen -- throw our hands up in the air and start over.
763 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
764 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700765 createEmptyDB(db);
766 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700767
Sunny Goyal42de82f2014-09-26 22:09:29 -0700768 /**
769 * Clears all the data for a fresh start.
770 */
771 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700772 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
773 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
774 onCreate(db);
775 }
776
Sunny Goyald2f38192015-02-25 10:46:34 -0800777 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700778 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
779 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
780 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700781 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700782 db.beginTransaction();
783 Cursor c = null;
784 SQLiteStatement updateStmt = null;
785
786 try {
787 // Only consider the primary user as other users can't have a shortcut.
788 long userSerial = UserManagerCompat.getInstance(mContext)
789 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
790 c = db.query(TABLE_FAVORITES, new String[] {
791 Favorites._ID,
792 Favorites.INTENT,
793 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
794 null, null, null, null);
795
796 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
797 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
798
799 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
800 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
801
802 while (c.moveToNext()) {
803 String intentDescription = c.getString(intentIndex);
804 Intent intent;
805 try {
806 intent = Intent.parseUri(intentDescription, 0);
807 } catch (URISyntaxException e) {
808 Log.e(TAG, "Unable to parse intent", e);
809 continue;
810 }
811
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700812 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700813 continue;
814 }
815
816 long id = c.getLong(idIndex);
817 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700818 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700819 }
820 db.setTransactionSuccessful();
821 } catch (SQLException ex) {
822 Log.w(TAG, "Error deduping shortcuts", ex);
823 } finally {
824 db.endTransaction();
825 if (c != null) {
826 c.close();
827 }
828 if (updateStmt != null) {
829 updateStmt.close();
830 }
831 }
832 }
833
834 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800835 * Recreates workspace table and migrates data to the new table.
836 */
837 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
838 db.beginTransaction();
839 try {
840 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
841 new String[] {LauncherSettings.WorkspaceScreens._ID},
842 null, null, null, null,
843 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
844 ArrayList<Long> sortedIDs = new ArrayList<Long>();
845 long maxId = 0;
846 try {
847 while (c.moveToNext()) {
848 Long id = c.getLong(0);
849 if (!sortedIDs.contains(id)) {
850 sortedIDs.add(id);
851 maxId = Math.max(maxId, id);
852 }
853 }
854 } finally {
855 c.close();
856 }
857
858 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700859 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800860
861 // Add all screen ids back
862 int total = sortedIDs.size();
863 for (int i = 0; i < total; i++) {
864 ContentValues values = new ContentValues();
865 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
866 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
867 addModifiedTime(values);
868 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
869 }
870 db.setTransactionSuccessful();
871 mMaxScreenId = maxId;
872 } catch (SQLException ex) {
873 // Old version remains, which means we wipe old data
874 Log.e(TAG, ex.getMessage(), ex);
875 return false;
876 } finally {
877 db.endTransaction();
878 }
879 return true;
880 }
881
Adam Cohen091440a2015-03-18 14:16:05 -0700882 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800883 db.beginTransaction();
884 try {
885 if (addRankColumn) {
886 // Insert new column for holding rank
887 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
888 }
889
890 // Get a map for folder ID to folder width
891 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
892 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
893 + " GROUP BY container;",
894 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
895
896 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800897 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
898 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800899 new Object[] {c.getLong(1) + 1, c.getLong(0)});
900 }
901
902 c.close();
903 db.setTransactionSuccessful();
904 } catch (SQLException ex) {
905 // Old version remains, which means we wipe old data
906 Log.e(TAG, ex.getMessage(), ex);
907 return false;
908 } finally {
909 db.endTransaction();
910 }
911 return true;
912 }
913
Kenny Guyed131872014-04-30 03:02:21 +0100914 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700915 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
916 // Default to the serial number of this user, for older
917 // shortcuts.
918 long userSerialNumber = userManager.getSerialNumberForUser(
919 UserHandleCompat.myUserHandle());
920 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
921 }
922
923 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100924 db.beginTransaction();
925 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700926 db.execSQL("ALTER TABLE favorites ADD COLUMN "
927 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100928 db.setTransactionSuccessful();
929 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100930 Log.e(TAG, ex.getMessage(), ex);
931 return false;
932 } finally {
933 db.endTransaction();
934 }
935 return true;
936 }
937
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700938 // Generates a new ID to use for an object in your database. This method should be only
939 // called from the main UI thread. As an exception, we do call it when we call the
940 // constructor from the worker thread; however, this doesn't extend until after the
941 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
942 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700943 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700944 public long generateNewItemId() {
945 if (mMaxItemId < 0) {
946 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700947 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 mMaxItemId += 1;
949 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700950 }
951
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700952 @Override
953 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
954 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
955 }
956
Chris Wren5dee7af2013-12-20 17:22:11 -0500957 public void checkId(String table, ContentValues values) {
958 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
959 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
960 mMaxScreenId = Math.max(id, mMaxScreenId);
961 } else {
962 mMaxItemId = Math.max(id, mMaxItemId);
963 }
964 }
965
Adam Cohendcd297f2013-06-18 13:13:40 -0700966 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800967 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700968 }
969
970 // Generates a new ID to use for an workspace screen in your database. This method
971 // should be only called from the main UI thread. As an exception, we do call it when we
972 // call the constructor from the worker thread; however, this doesn't extend until after the
973 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
974 // after that point
975 public long generateNewScreenId() {
976 if (mMaxScreenId < 0) {
977 throw new RuntimeException("Error: max screen id was not initialized");
978 }
979 mMaxScreenId += 1;
980 return mMaxScreenId;
981 }
982
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800984 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800985 }
986
Adam Cohen091440a2015-03-18 14:16:05 -0700987 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700988 // 1. Ensure that externally added items have a valid item id
989 long id = generateNewItemId();
990 values.put(LauncherSettings.Favorites._ID, id);
991
992 // 2. In the case of an app widget, and if no app widget id is specified, we
993 // attempt allocate and bind the widget.
994 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
995 if (itemType != null &&
996 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
997 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
998
999 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1000 ComponentName cn = ComponentName.unflattenFromString(
1001 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1002
1003 if (cn != null) {
1004 try {
1005 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001006 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001007 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001008 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001009 }
1010 } catch (RuntimeException e) {
1011 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001012 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001013 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001014 } else {
1015 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001016 }
1017 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001018
1019 // Add screen id if not present
1020 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1021 if (!addScreenIdIfNecessary(screenId)) {
1022 return false;
1023 }
Adam Cohena043fa82014-07-23 14:49:38 -07001024 return true;
1025 }
1026
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001027 // Returns true of screen id exists, or if successfully added
1028 private boolean addScreenIdIfNecessary(long screenId) {
1029 if (!hasScreenId(screenId)) {
1030 int rank = getMaxScreenRank() + 1;
1031
1032 ContentValues v = new ContentValues();
1033 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1034 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1035 if (dbInsertAndCheck(this, getWritableDatabase(),
1036 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1037 return false;
1038 }
1039 }
1040 return true;
1041 }
1042
1043 private boolean hasScreenId(long screenId) {
1044 SQLiteDatabase db = getWritableDatabase();
1045 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1046 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1047 if (c != null) {
1048 int count = c.getCount();
1049 c.close();
1050 return count > 0;
1051 } else {
1052 return false;
1053 }
1054 }
1055
1056 private int getMaxScreenRank() {
1057 SQLiteDatabase db = getWritableDatabase();
1058 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1059 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1060
1061 // get the result
1062 final int maxRankIndex = 0;
1063 int rank = -1;
1064 if (c != null && c.moveToNext()) {
1065 rank = c.getInt(maxRankIndex);
1066 }
1067 if (c != null) {
1068 c.close();
1069 }
1070
1071 return rank;
1072 }
1073
Adam Cohen091440a2015-03-18 14:16:05 -07001074 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001075 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001076 // TODO: Use multiple loaders with fall-back and transaction.
1077 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001078
1079 // Add the screens specified by the items above
1080 Collections.sort(screenIds);
1081 int rank = 0;
1082 ContentValues values = new ContentValues();
1083 for (Long id : screenIds) {
1084 values.clear();
1085 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1086 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1087 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1088 throw new RuntimeException("Failed initialize screen table"
1089 + "from default layout");
1090 }
1091 rank++;
1092 }
1093
1094 // Ensure that the max ids are initialized
1095 mMaxItemId = initializeMaxItemId(db);
1096 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001097
Adam Cohen71483f42014-05-15 14:04:01 -07001098 return count;
1099 }
1100
Adam Cohen091440a2015-03-18 14:16:05 -07001101 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001102 final ContentResolver resolver = mContext.getContentResolver();
1103 Cursor c = null;
1104 int count = 0;
1105 int curScreen = 0;
1106
1107 try {
1108 c = resolver.query(uri, null, null, null, "title ASC");
1109 } catch (Exception e) {
1110 // Ignore
1111 }
1112
Dan Sandlerd5024042014-01-09 15:01:33 -05001113 // We already have a favorites database in the old provider
1114 if (c != null) {
1115 try {
1116 if (c.getCount() > 0) {
1117 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1118 final int intentIndex
1119 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1120 final int titleIndex
1121 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1122 final int iconTypeIndex
1123 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1124 final int iconIndex
1125 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1126 final int iconPackageIndex
1127 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1128 final int iconResourceIndex
1129 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1130 final int containerIndex
1131 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1132 final int itemTypeIndex
1133 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1134 final int screenIndex
1135 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1136 final int cellXIndex
1137 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1138 final int cellYIndex
1139 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001140 final int profileIndex
1141 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001142
1143 int i = 0;
1144 int curX = 0;
1145 int curY = 0;
1146
1147 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001148 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1149 final int width = (int) profile.numColumns;
1150 final int height = (int) profile.numRows;
1151 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001152
1153 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1154
Adam Cohen72960972014-01-15 18:13:55 -08001155 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1156 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001157 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001158
1159 while (c.moveToNext()) {
1160 final int itemType = c.getInt(itemTypeIndex);
1161 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1162 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1163 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1164 continue;
1165 }
1166
1167 final int cellX = c.getInt(cellXIndex);
1168 final int cellY = c.getInt(cellYIndex);
1169 final int screen = c.getInt(screenIndex);
1170 int container = c.getInt(containerIndex);
1171 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001172
1173 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1174 UserHandleCompat userHandle;
1175 final long userSerialNumber;
1176 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1177 userSerialNumber = c.getInt(profileIndex);
1178 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1179 } else {
1180 // Default to the serial number of this user, for older
1181 // shortcuts.
1182 userHandle = UserHandleCompat.myUserHandle();
1183 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1184 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001185
1186 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001187 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001188 continue;
1189 }
1190
Dan Sandlerd5024042014-01-09 15:01:33 -05001191 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001192
1193 final Intent intent;
1194 final ComponentName cn;
1195 try {
1196 intent = Intent.parseUri(intentStr, 0);
1197 } catch (URISyntaxException e) {
1198 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001199 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001200 continue;
1201 }
1202
1203 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001204 if (TextUtils.isEmpty(intentStr)) {
1205 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001206 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001207 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001208 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001209 !LauncherModel.isValidPackageActivity(mContext, cn,
1210 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001211 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001212 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001213 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001214 } else if (container ==
1215 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1216 // Dedupe icons directly on the workspace
1217
Adam Cohen556f6132014-01-15 15:18:08 -08001218 // Canonicalize
1219 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001220 // does not, so we clear that out to keep them the same.
1221 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001222 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001223 int flags = intent.getFlags();
1224 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001225 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001226 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001227 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001228 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001229 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001230 } else {
1231 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001232 }
1233 }
1234 }
1235
1236 ContentValues values = new ContentValues(c.getColumnCount());
1237 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1238 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1239 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1240 values.put(LauncherSettings.Favorites.ICON_TYPE,
1241 c.getInt(iconTypeIndex));
1242 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1243 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1244 c.getString(iconPackageIndex));
1245 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1246 c.getString(iconResourceIndex));
1247 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1248 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001249 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001250
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001251 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1252 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001253 }
1254
1255 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1256 // In a folder or in the hotseat, preserve position
1257 values.put(LauncherSettings.Favorites.SCREEN, screen);
1258 values.put(LauncherSettings.Favorites.CELLX, cellX);
1259 values.put(LauncherSettings.Favorites.CELLY, cellY);
1260 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001261 // For items contained directly on one of the workspace screen,
1262 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001263 }
1264
1265 values.put(LauncherSettings.Favorites.CONTAINER, container);
1266
Adam Cohen72960972014-01-15 18:13:55 -08001267 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1268 shortcuts.add(values);
1269 } else {
1270 folders.add(values);
1271 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001272 }
1273
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001274 // Now that we have all the hotseat icons, let's go through them left-right
1275 // and assign valid locations for them in the new hotseat
1276 final int N = hotseat.size();
1277 for (int idx=0; idx<N; idx++) {
1278 int hotseatX = hotseat.keyAt(idx);
1279 ContentValues values = hotseat.valueAt(idx);
1280
Adam Cohen2e6da152015-05-06 11:42:25 -07001281 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001282 // let's drop this in the next available hole in the hotseat
1283 while (++hotseatX < hotseatWidth) {
1284 if (hotseat.get(hotseatX) == null) {
1285 // found a spot! move it here
1286 values.put(LauncherSettings.Favorites.SCREEN,
1287 hotseatX);
1288 break;
1289 }
1290 }
1291 }
1292 if (hotseatX >= hotseatWidth) {
1293 // no room for you in the hotseat? it's off to the desktop with you
1294 values.put(LauncherSettings.Favorites.CONTAINER,
1295 Favorites.CONTAINER_DESKTOP);
1296 }
1297 }
1298
Adam Cohen72960972014-01-15 18:13:55 -08001299 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1300 // Folders first
1301 allItems.addAll(folders);
1302 // Then shortcuts
1303 allItems.addAll(shortcuts);
1304
1305 // Layout all the folders
1306 for (ContentValues values: allItems) {
1307 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1308 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1309 // Hotseat items and folder items have already had their
1310 // location information set. Nothing to be done here.
1311 continue;
1312 }
1313 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1314 values.put(LauncherSettings.Favorites.CELLX, curX);
1315 values.put(LauncherSettings.Favorites.CELLY, curY);
1316 curX = (curX + 1) % width;
1317 if (curX == 0) {
1318 curY = (curY + 1);
1319 }
1320 // Leave the last row of icons blank on every screen
1321 if (curY == height - 1) {
1322 curScreen = (int) generateNewScreenId();
1323 curY = 0;
1324 }
1325 }
1326
1327 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001328 db.beginTransaction();
1329 try {
Adam Cohen72960972014-01-15 18:13:55 -08001330 for (ContentValues row: allItems) {
1331 if (row == null) continue;
1332 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001333 < 0) {
1334 return;
1335 } else {
1336 count++;
1337 }
1338 }
1339 db.setTransactionSuccessful();
1340 } finally {
1341 db.endTransaction();
1342 }
1343 }
1344
1345 db.beginTransaction();
1346 try {
1347 for (i=0; i<=curScreen; i++) {
1348 final ContentValues values = new ContentValues();
1349 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1350 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1351 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1352 < 0) {
1353 return;
1354 }
1355 }
1356 db.setTransactionSuccessful();
1357 } finally {
1358 db.endTransaction();
1359 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001360
1361 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001362 }
1363 } finally {
1364 c.close();
1365 }
1366 }
1367
Sunny Goyala1365452015-10-01 15:46:24 -07001368 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1369 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001370
1371 // ensure that new screens are created to hold these icons
1372 setFlagJustLoadedOldDb();
1373
1374 // Update max IDs; very important since we just grabbed IDs from another database
1375 mMaxItemId = initializeMaxItemId(db);
1376 mMaxScreenId = initializeMaxScreenId(db);
1377 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1378 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001379 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001380
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001381 /**
1382 * @return the max _id in the provided table.
1383 */
Adam Cohen091440a2015-03-18 14:16:05 -07001384 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001385 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1386 // get the result
1387 long id = -1;
1388 if (c != null && c.moveToNext()) {
1389 id = c.getLong(0);
1390 }
1391 if (c != null) {
1392 c.close();
1393 }
1394
1395 if (id == -1) {
1396 throw new RuntimeException("Error: could not query max id in " + table);
1397 }
1398
1399 return id;
1400 }
1401
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001402 static class SqlArguments {
1403 public final String table;
1404 public final String where;
1405 public final String[] args;
1406
1407 SqlArguments(Uri url, String where, String[] args) {
1408 if (url.getPathSegments().size() == 1) {
1409 this.table = url.getPathSegments().get(0);
1410 this.where = where;
1411 this.args = args;
1412 } else if (url.getPathSegments().size() != 2) {
1413 throw new IllegalArgumentException("Invalid URI: " + url);
1414 } else if (!TextUtils.isEmpty(where)) {
1415 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1416 } else {
1417 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001418 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001419 this.args = null;
1420 }
1421 }
1422
1423 SqlArguments(Uri url) {
1424 if (url.getPathSegments().size() == 1) {
1425 table = url.getPathSegments().get(0);
1426 where = null;
1427 args = null;
1428 } else {
1429 throw new IllegalArgumentException("Invalid URI: " + url);
1430 }
1431 }
1432 }
Adam Cohen72960972014-01-15 18:13:55 -08001433}