blob: a6fd282422bcf0e54ab21320d9aae48a3aa8f164 [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;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070068 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080069 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Sunny Goyal5c97f512015-05-19 16:03:28 -070071 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072
Sunny Goyale5bb7052015-07-27 14:36:07 -070073 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070074
Sunny Goyal18b640c2015-04-17 09:24:01 -070075 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
76 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080077 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070079 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
80
Sunny Goyal383c5072015-06-12 21:18:53 -070081 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070082 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080087 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080089 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 return true;
92 }
93
Winson Chung0b560dd2014-01-21 13:00:26 -080094 public boolean wasNewDbCreated() {
95 return mOpenHelper.wasNewDbCreated();
96 }
97
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
99 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700100 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public String getType(Uri uri) {
105 SqlArguments args = new SqlArguments(uri, null, null);
106 if (TextUtils.isEmpty(args.where)) {
107 return "vnd.android.cursor.dir/" + args.table;
108 } else {
109 return "vnd.android.cursor.item/" + args.table;
110 }
111 }
112
113 @Override
114 public Cursor query(Uri uri, String[] projection, String selection,
115 String[] selectionArgs, String sortOrder) {
116
117 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
118 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
119 qb.setTables(args.table);
120
Romain Guy73b979d2009-06-09 12:57:21 -0700121 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
123 result.setNotificationUri(getContext().getContentResolver(), uri);
124
125 return result;
126 }
127
Adam Cohen091440a2015-03-18 14:16:05 -0700128 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500130 if (values == null) {
131 throw new RuntimeException("Error: attempting to insert null values");
132 }
Adam Cohen71483f42014-05-15 14:04:01 -0700133 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 throw new RuntimeException("Error: attempting to add item without specifying an id");
135 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500136 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 return db.insert(table, nullColumnHack, values);
138 }
139
Sunny Goyald1064182015-08-13 12:08:30 -0700140 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700141 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700142 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
143 if (app != null) {
144 app.reloadWorkspace();
145 }
146 }
147 }
148
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149 @Override
150 public Uri insert(Uri uri, ContentValues initialValues) {
151 SqlArguments args = new SqlArguments(uri);
152
Sunny Goyald1064182015-08-13 12:08:30 -0700153 // In very limited cases, we support system|signature permission apps to modify the db.
154 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700155 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
156 return null;
157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400161 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800163 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700166 notifyListeners();
167
Sunny Goyalc74e4192015-09-08 14:01:03 -0700168 if (Utilities.ATLEAST_MARSHMALLOW) {
169 reloadLauncherIfExternal();
170 } else {
171 // Deprecated behavior to support legacy devices which rely on provider callbacks.
172 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
173 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
174 app.reloadWorkspace();
175 }
176
177 String notify = uri.getQueryParameter("notify");
178 if (notify == null || "true".equals(notify)) {
179 getContext().getContentResolver().notifyChange(uri, null);
180 }
181 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 return uri;
183 }
184
Adam Cohena043fa82014-07-23 14:49:38 -0700185
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186 @Override
187 public int bulkInsert(Uri uri, ContentValues[] values) {
188 SqlArguments args = new SqlArguments(uri);
189
190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
191 db.beginTransaction();
192 try {
193 int numValues = values.length;
194 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700196 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
197 return 0;
198 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199 }
200 db.setTransactionSuccessful();
201 } finally {
202 db.endTransaction();
203 }
204
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700205 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700206 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800207 return values.length;
208 }
209
210 @Override
Yura085c8532014-02-11 15:15:29 +0000211 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
212 throws OperationApplicationException {
213 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
214 db.beginTransaction();
215 try {
216 ContentProviderResult[] result = super.applyBatch(operations);
217 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700218 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000219 return result;
220 } finally {
221 db.endTransaction();
222 }
223 }
224
225 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800226 public int delete(Uri uri, String selection, String[] selectionArgs) {
227 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
228
229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
230 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700231 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232
Sunny Goyald1064182015-08-13 12:08:30 -0700233 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 return count;
235 }
236
237 @Override
238 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
239 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
240
Chris Wren1ada10d2013-09-13 18:01:38 -0400241 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
243 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700244 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800245
Sunny Goyald1064182015-08-13 12:08:30 -0700246 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800247 return count;
248 }
249
Sunny Goyal7779d622015-06-11 16:18:39 -0700250 @Override
251 public Bundle call(String method, String arg, Bundle extras) {
252 if (Binder.getCallingUid() != Process.myUid()) {
253 return null;
254 }
255
256 switch (method) {
257 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
258 Bundle result = new Bundle();
259 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
260 getContext().getSharedPreferences(
261 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
262 .getBoolean(arg, extras.getBoolean(
263 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
264 return result;
265 }
266 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
267 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
268 getContext().getSharedPreferences(
269 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
270 .edit().putBoolean(arg, value).apply();
271 if (mListener != null) {
272 mListener.onSettingsChanged(arg, value);
273 }
274 Bundle result = new Bundle();
275 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
276 return result;
277 }
278 }
279 return null;
280 }
281
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700282 /**
283 * Deletes any empty folder from the DB.
284 * @return Ids of deleted folders.
285 */
286 public List<Long> deleteEmptyFolders() {
287 ArrayList<Long> folderIds = new ArrayList<Long>();
288 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
289 db.beginTransaction();
290 try {
291 // Select folders whose id do not match any container value.
292 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
293 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
294 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
295 LauncherSettings.Favorites.CONTAINER + " FROM "
296 + TABLE_FAVORITES + ")";
297 Cursor c = db.query(TABLE_FAVORITES,
298 new String[] {LauncherSettings.Favorites._ID},
299 selection, null, null, null, null);
300 while (c.moveToNext()) {
301 folderIds.add(c.getLong(0));
302 }
303 c.close();
304 if (folderIds.size() > 0) {
305 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
306 LauncherSettings.Favorites._ID, folderIds), null);
307 }
308 db.setTransactionSuccessful();
309 } catch (SQLException ex) {
310 Log.e(TAG, ex.getMessage(), ex);
311 folderIds.clear();
312 } finally {
313 db.endTransaction();
314 }
315 return folderIds;
316 }
317
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700318 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400319 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400320 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700321 if (mListener != null) {
322 mListener.onLauncherProviderChange();
323 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400324 }
325
Adam Cohen091440a2015-03-18 14:16:05 -0700326 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400327 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 }
329
Adam Cohendcd297f2013-06-18 13:13:40 -0700330 public long generateNewItemId() {
331 return mOpenHelper.generateNewItemId();
332 }
333
334 public long generateNewScreenId() {
335 return mOpenHelper.generateNewScreenId();
336 }
337
Brian Muramatsu5524b492012-10-02 16:55:54 -0700338 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700339 * Clears all the data for a fresh start.
340 */
341 synchronized public void createEmptyDB() {
342 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
343 }
344
Sunny Goyal33d44382014-10-16 09:24:19 -0700345 public void clearFlagEmptyDbCreated() {
346 String spKey = LauncherAppState.getSharedPreferencesKey();
347 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
348 .edit()
349 .remove(EMPTY_DATABASE_CREATED)
350 .commit();
351 }
352
Sunny Goyal42de82f2014-09-26 22:09:29 -0700353 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700354 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700355 * 1) From the app restrictions
356 * 2) From a package provided by play store
357 * 3) From a partner configuration APK, already in the system image
358 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700359 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700360 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400361 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700362 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700363
Winson Chungc763c4e2013-07-19 13:49:06 -0700364 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500365 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200366
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700367 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
368 if (loader == null) {
369 loader = AutoInstallsLayout.get(getContext(),
370 mOpenHelper.mAppWidgetHost, mOpenHelper);
371 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700372 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700373 final Partner partner = Partner.get(getContext().getPackageManager());
374 if (partner != null && partner.hasDefaultLayout()) {
375 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700376 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700377 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700378 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700379 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
380 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700381 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700382 }
383 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700384
Sunny Goyal9d219682014-10-23 14:21:02 -0700385 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700386 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700387 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700388 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800389
390 // There might be some partially restored DB items, due to buggy restore logic in
391 // previous versions of launcher.
392 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700393 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700394 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
395 && usingExternallyProvidedLayout) {
396 // Unable to load external layout. Cleanup and load the internal layout.
397 createEmptyDB();
398 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
399 getDefaultLayoutParser());
400 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700401 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700402 }
403 }
404
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700405 /**
406 * Creates workspace loader from an XML resource listed in the app restrictions.
407 *
408 * @return the loader if the restrictions are set and the resource exists; null otherwise.
409 */
410 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
411 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
412 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700413 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700414 return null;
415 }
416
417 Context ctx = getContext();
418 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
419 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700420 if (bundle == null) {
421 return null;
422 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700423
Sunny Goyal35ca8732015-04-06 10:45:31 -0700424 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700425 if (packageName != null) {
426 try {
427 Resources targetResources = ctx.getPackageManager()
428 .getResourcesForApplication(packageName);
429 return AutoInstallsLayout.get(ctx, packageName, targetResources,
430 mOpenHelper.mAppWidgetHost, mOpenHelper);
431 } catch (NameNotFoundException e) {
432 Log.e(TAG, "Target package for restricted profile not found", e);
433 return null;
434 }
435 }
436 return null;
437 }
438
Sunny Goyal9d219682014-10-23 14:21:02 -0700439 private DefaultLayoutParser getDefaultLayoutParser() {
440 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700441 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700442 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
443 mOpenHelper, getContext().getResources(), defaultLayout);
444 }
445
Dan Sandlerd5024042014-01-09 15:01:33 -0500446 public void migrateLauncher2Shortcuts() {
447 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400448 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500449 }
450
Sunny Goyal08f72612015-01-05 13:41:43 -0800451 public void updateFolderItemsRank() {
452 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
453 }
454
Sunny Goyal5c97f512015-05-19 16:03:28 -0700455 public void convertShortcutsToLauncherActivities() {
456 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
457 }
458
459
Dan Sandlerd5024042014-01-09 15:01:33 -0500460 public void deleteDatabase() {
461 // Are you sure? (y/n)
462 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500463 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500464 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500465 if (dbFile.exists()) {
466 SQLiteDatabase.deleteDatabase(dbFile);
467 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500468 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700469 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500470 }
471
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700472 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800473 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700474 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700475 private long mMaxItemId = -1;
476 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477
Winson Chung0b560dd2014-01-21 13:00:26 -0800478 private boolean mNewDbCreated = false;
479
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700480 @Thunk LauncherProviderChangeListener mListener;
481
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800482 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100483 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700485 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700486
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700487 // Table creation sometimes fails silently, which leads to a crash loop.
488 // This way, we will try to create a table every time after crash, so the device
489 // would eventually be able to recover.
490 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
491 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
492 // This operation is a no-op if the table already exists.
493 addFavoritesTable(getWritableDatabase(), true);
494 addWorkspacesTable(getWritableDatabase(), true);
495 }
496
Winson Chung3d503fb2011-07-13 17:25:49 -0700497 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
498 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700499 if (mMaxItemId == -1) {
500 mMaxItemId = initializeMaxItemId(getWritableDatabase());
501 }
502 if (mMaxScreenId == -1) {
503 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700504 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800505 }
506
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700507 private boolean tableExists(String tableName) {
508 Cursor c = getReadableDatabase().query(
509 true, "sqlite_master", new String[] {"tbl_name"},
510 "tbl_name = ?", new String[] {tableName},
511 null, null, null, null, null);
512 try {
513 return c.getCount() > 0;
514 } finally {
515 c.close();
516 }
517 }
518
Winson Chung0b560dd2014-01-21 13:00:26 -0800519 public boolean wasNewDbCreated() {
520 return mNewDbCreated;
521 }
522
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800523 @Override
524 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800525 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700526
Adam Cohendcd297f2013-06-18 13:13:40 -0700527 mMaxItemId = 1;
528 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800529 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700530
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700531 addFavoritesTable(db, false);
532 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800533
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700534 // Database was just created, so wipe any previous widgets
535 if (mAppWidgetHost != null) {
536 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700537
538 /**
539 * Send notification that we've deleted the {@link AppWidgetHost},
540 * probably as part of the initial database creation. The receiver may
541 * want to re-call {@link AppWidgetHost#startListening()} to ensure
542 * callbacks are correctly set.
543 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700544 new MainThreadExecutor().execute(new Runnable() {
545
546 @Override
547 public void run() {
548 if (mListener != null) {
549 mListener.onAppWidgetHostReset();
550 }
551 }
552 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800553 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700554
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800555 // Fresh and clean launcher DB.
556 mMaxItemId = initializeMaxItemId(db);
557 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700558
559 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700560 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 }
562
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700563 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
564 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
565 long userSerialNumber = userManager.getSerialNumberForUser(
566 UserHandleCompat.myUserHandle());
567 String ifNotExists = optional ? " IF NOT EXISTS " : "";
568
569 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
570 "_id INTEGER PRIMARY KEY," +
571 "title TEXT," +
572 "intent TEXT," +
573 "container INTEGER," +
574 "screen INTEGER," +
575 "cellX INTEGER," +
576 "cellY INTEGER," +
577 "spanX INTEGER," +
578 "spanY INTEGER," +
579 "itemType INTEGER," +
580 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
581 "isShortcut INTEGER," +
582 "iconType INTEGER," +
583 "iconPackage TEXT," +
584 "iconResource TEXT," +
585 "icon BLOB," +
586 "uri TEXT," +
587 "displayMode INTEGER," +
588 "appWidgetProvider TEXT," +
589 "modified INTEGER NOT NULL DEFAULT 0," +
590 "restored INTEGER NOT NULL DEFAULT 0," +
591 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
592 "rank INTEGER NOT NULL DEFAULT 0," +
593 "options INTEGER NOT NULL DEFAULT 0" +
594 ");");
595 }
596
597 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
598 String ifNotExists = optional ? " IF NOT EXISTS " : "";
599 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800600 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400601 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
602 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700603 ");");
604 }
605
Adam Cohen119285e2014-04-02 16:59:08 -0700606 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700607 // Delete items directly on the workspace who's screen id doesn't exist
608 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
609 // AND container = -100"
610 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
611 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700612 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700613 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
614 " AND " +
615 LauncherSettings.Favorites.CONTAINER + " = " +
616 LauncherSettings.Favorites.CONTAINER_DESKTOP;
617 db.execSQL(removeOrphanedDesktopItems);
618
619 // Delete items contained in folders which no longer exist (after above statement)
620 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
621 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
622 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
623 " WHERE " +
624 LauncherSettings.Favorites.CONTAINER + " <> " +
625 LauncherSettings.Favorites.CONTAINER_DESKTOP +
626 " AND "
627 + LauncherSettings.Favorites.CONTAINER + " <> " +
628 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
629 " AND "
630 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
631 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
632 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
633 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
634 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700635 }
636
Winson Chungc763c4e2013-07-19 13:49:06 -0700637 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400638 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700639 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800640 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700641 }
642
Winson Chungc763c4e2013-07-19 13:49:06 -0700643 private void setFlagEmptyDbCreated() {
644 String spKey = LauncherAppState.getSharedPreferencesKey();
645 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800646 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700647 }
648
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 @Override
650 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700651 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800652 switch (oldVersion) {
653 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800654 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800655 case 12: {
656 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
657 // to persist workspace screens and their relative order.
658 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700659 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800660 }
661 case 13: {
662 db.beginTransaction();
663 try {
664 // Insert new column for holding widget provider name
665 db.execSQL("ALTER TABLE favorites " +
666 "ADD COLUMN appWidgetProvider TEXT;");
667 db.setTransactionSuccessful();
668 } catch (SQLException ex) {
669 Log.e(TAG, ex.getMessage(), ex);
670 // Old version remains, which means we wipe old data
671 break;
672 } finally {
673 db.endTransaction();
674 }
675 }
676 case 14: {
677 db.beginTransaction();
678 try {
679 // Insert new column for holding update timestamp
680 db.execSQL("ALTER TABLE favorites " +
681 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
682 db.execSQL("ALTER TABLE workspaceScreens " +
683 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
684 db.setTransactionSuccessful();
685 } catch (SQLException ex) {
686 Log.e(TAG, ex.getMessage(), ex);
687 // Old version remains, which means we wipe old data
688 break;
689 } finally {
690 db.endTransaction();
691 }
692 }
693 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700694 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800695 // Old version remains, which means we wipe old data
696 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 }
698 }
699 case 16: {
700 // We use the db version upgrade here to identify users who may not have seen
701 // clings yet (because they weren't available), but for whom the clings are now
702 // available (tablet users). Because one of the possible cling flows (migration)
703 // is very destructive (wipes out workspaces), we want to prevent this from showing
704 // until clear data. We do so by marking that the clings have been shown.
705 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
706 }
707 case 17: {
708 // No-op
709 }
710 case 18: {
711 // Due to a data loss bug, some users may have items associated with screen ids
712 // which no longer exist. Since this can cause other problems, and since the user
713 // will never see these items anyway, we use database upgrade as an opportunity to
714 // clean things up.
715 removeOrphanedItems(db);
716 }
717 case 19: {
718 // Add userId column
719 if (!addProfileColumn(db)) {
720 // Old version remains, which means we wipe old data
721 break;
722 }
723 }
724 case 20:
725 if (!updateFolderItemsRank(db, true)) {
726 break;
727 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800728 case 21:
729 // Recreate workspace table with screen id a primary key
730 if (!recreateWorkspaceTable(db)) {
731 break;
732 }
733 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700734 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
735 // Old version remains, which means we wipe old data
736 break;
737 }
738 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700739 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700740 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700741 case 24:
742 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700743 case 25:
744 convertShortcutsToLauncherActivities(db);
745 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800746 // DB Upgraded successfully
747 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400748 }
749 }
750
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 // DB was not upgraded
752 Log.w(TAG, "Destroying all old data.");
753 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800754 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800755
Adam Cohen9b1d0622014-05-21 19:01:57 -0700756 @Override
757 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
758 // This shouldn't happen -- throw our hands up in the air and start over.
759 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
760 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700761 createEmptyDB(db);
762 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700763
Sunny Goyal42de82f2014-09-26 22:09:29 -0700764 /**
765 * Clears all the data for a fresh start.
766 */
767 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700768 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
769 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
770 onCreate(db);
771 }
772
Sunny Goyald2f38192015-02-25 10:46:34 -0800773 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700774 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
775 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
776 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700777 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700778 db.beginTransaction();
779 Cursor c = null;
780 SQLiteStatement updateStmt = null;
781
782 try {
783 // Only consider the primary user as other users can't have a shortcut.
784 long userSerial = UserManagerCompat.getInstance(mContext)
785 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
786 c = db.query(TABLE_FAVORITES, new String[] {
787 Favorites._ID,
788 Favorites.INTENT,
789 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
790 null, null, null, null);
791
792 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
793 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
794
795 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
796 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
797
798 while (c.moveToNext()) {
799 String intentDescription = c.getString(intentIndex);
800 Intent intent;
801 try {
802 intent = Intent.parseUri(intentDescription, 0);
803 } catch (URISyntaxException e) {
804 Log.e(TAG, "Unable to parse intent", e);
805 continue;
806 }
807
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700808 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700809 continue;
810 }
811
812 long id = c.getLong(idIndex);
813 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700814 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700815 }
816 db.setTransactionSuccessful();
817 } catch (SQLException ex) {
818 Log.w(TAG, "Error deduping shortcuts", ex);
819 } finally {
820 db.endTransaction();
821 if (c != null) {
822 c.close();
823 }
824 if (updateStmt != null) {
825 updateStmt.close();
826 }
827 }
828 }
829
830 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800831 * Recreates workspace table and migrates data to the new table.
832 */
833 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
834 db.beginTransaction();
835 try {
836 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
837 new String[] {LauncherSettings.WorkspaceScreens._ID},
838 null, null, null, null,
839 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
840 ArrayList<Long> sortedIDs = new ArrayList<Long>();
841 long maxId = 0;
842 try {
843 while (c.moveToNext()) {
844 Long id = c.getLong(0);
845 if (!sortedIDs.contains(id)) {
846 sortedIDs.add(id);
847 maxId = Math.max(maxId, id);
848 }
849 }
850 } finally {
851 c.close();
852 }
853
854 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700855 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800856
857 // Add all screen ids back
858 int total = sortedIDs.size();
859 for (int i = 0; i < total; i++) {
860 ContentValues values = new ContentValues();
861 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
862 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
863 addModifiedTime(values);
864 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
865 }
866 db.setTransactionSuccessful();
867 mMaxScreenId = maxId;
868 } catch (SQLException ex) {
869 // Old version remains, which means we wipe old data
870 Log.e(TAG, ex.getMessage(), ex);
871 return false;
872 } finally {
873 db.endTransaction();
874 }
875 return true;
876 }
877
Adam Cohen091440a2015-03-18 14:16:05 -0700878 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800879 db.beginTransaction();
880 try {
881 if (addRankColumn) {
882 // Insert new column for holding rank
883 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
884 }
885
886 // Get a map for folder ID to folder width
887 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
888 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
889 + " GROUP BY container;",
890 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
891
892 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800893 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
894 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800895 new Object[] {c.getLong(1) + 1, c.getLong(0)});
896 }
897
898 c.close();
899 db.setTransactionSuccessful();
900 } catch (SQLException ex) {
901 // Old version remains, which means we wipe old data
902 Log.e(TAG, ex.getMessage(), ex);
903 return false;
904 } finally {
905 db.endTransaction();
906 }
907 return true;
908 }
909
Kenny Guyed131872014-04-30 03:02:21 +0100910 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700911 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
912 // Default to the serial number of this user, for older
913 // shortcuts.
914 long userSerialNumber = userManager.getSerialNumberForUser(
915 UserHandleCompat.myUserHandle());
916 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
917 }
918
919 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100920 db.beginTransaction();
921 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700922 db.execSQL("ALTER TABLE favorites ADD COLUMN "
923 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100924 db.setTransactionSuccessful();
925 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100926 Log.e(TAG, ex.getMessage(), ex);
927 return false;
928 } finally {
929 db.endTransaction();
930 }
931 return true;
932 }
933
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700934 // Generates a new ID to use for an object in your database. This method should be only
935 // called from the main UI thread. As an exception, we do call it when we call the
936 // constructor from the worker thread; however, this doesn't extend until after the
937 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
938 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700939 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700940 public long generateNewItemId() {
941 if (mMaxItemId < 0) {
942 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700943 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700944 mMaxItemId += 1;
945 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700946 }
947
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700948 @Override
949 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
950 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
951 }
952
Chris Wren5dee7af2013-12-20 17:22:11 -0500953 public void checkId(String table, ContentValues values) {
954 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
955 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
956 mMaxScreenId = Math.max(id, mMaxScreenId);
957 } else {
958 mMaxItemId = Math.max(id, mMaxItemId);
959 }
960 }
961
Adam Cohendcd297f2013-06-18 13:13:40 -0700962 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800963 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700964 }
965
966 // Generates a new ID to use for an workspace screen in your database. This method
967 // should be only called from the main UI thread. As an exception, we do call it when we
968 // call the constructor from the worker thread; however, this doesn't extend until after the
969 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
970 // after that point
971 public long generateNewScreenId() {
972 if (mMaxScreenId < 0) {
973 throw new RuntimeException("Error: max screen id was not initialized");
974 }
975 mMaxScreenId += 1;
976 return mMaxScreenId;
977 }
978
Adam Cohendcd297f2013-06-18 13:13:40 -0700979 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800980 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800981 }
982
Adam Cohen091440a2015-03-18 14:16:05 -0700983 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700984 // 1. Ensure that externally added items have a valid item id
985 long id = generateNewItemId();
986 values.put(LauncherSettings.Favorites._ID, id);
987
988 // 2. In the case of an app widget, and if no app widget id is specified, we
989 // attempt allocate and bind the widget.
990 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
991 if (itemType != null &&
992 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
993 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
994
995 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
996 ComponentName cn = ComponentName.unflattenFromString(
997 values.getAsString(Favorites.APPWIDGET_PROVIDER));
998
999 if (cn != null) {
1000 try {
1001 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001002 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001003 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001004 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001005 }
1006 } catch (RuntimeException e) {
1007 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001008 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001009 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001010 } else {
1011 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001012 }
1013 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001014
1015 // Add screen id if not present
1016 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1017 if (!addScreenIdIfNecessary(screenId)) {
1018 return false;
1019 }
Adam Cohena043fa82014-07-23 14:49:38 -07001020 return true;
1021 }
1022
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001023 // Returns true of screen id exists, or if successfully added
1024 private boolean addScreenIdIfNecessary(long screenId) {
1025 if (!hasScreenId(screenId)) {
1026 int rank = getMaxScreenRank() + 1;
1027
1028 ContentValues v = new ContentValues();
1029 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1030 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1031 if (dbInsertAndCheck(this, getWritableDatabase(),
1032 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1033 return false;
1034 }
1035 }
1036 return true;
1037 }
1038
1039 private boolean hasScreenId(long screenId) {
1040 SQLiteDatabase db = getWritableDatabase();
1041 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1042 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1043 if (c != null) {
1044 int count = c.getCount();
1045 c.close();
1046 return count > 0;
1047 } else {
1048 return false;
1049 }
1050 }
1051
1052 private int getMaxScreenRank() {
1053 SQLiteDatabase db = getWritableDatabase();
1054 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1055 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1056
1057 // get the result
1058 final int maxRankIndex = 0;
1059 int rank = -1;
1060 if (c != null && c.moveToNext()) {
1061 rank = c.getInt(maxRankIndex);
1062 }
1063 if (c != null) {
1064 c.close();
1065 }
1066
1067 return rank;
1068 }
1069
Adam Cohen091440a2015-03-18 14:16:05 -07001070 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001071 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001072 // TODO: Use multiple loaders with fall-back and transaction.
1073 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001074
1075 // Add the screens specified by the items above
1076 Collections.sort(screenIds);
1077 int rank = 0;
1078 ContentValues values = new ContentValues();
1079 for (Long id : screenIds) {
1080 values.clear();
1081 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1082 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1083 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1084 throw new RuntimeException("Failed initialize screen table"
1085 + "from default layout");
1086 }
1087 rank++;
1088 }
1089
1090 // Ensure that the max ids are initialized
1091 mMaxItemId = initializeMaxItemId(db);
1092 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001093
Adam Cohen71483f42014-05-15 14:04:01 -07001094 return count;
1095 }
1096
Adam Cohen091440a2015-03-18 14:16:05 -07001097 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001098 final ContentResolver resolver = mContext.getContentResolver();
1099 Cursor c = null;
1100 int count = 0;
1101 int curScreen = 0;
1102
1103 try {
1104 c = resolver.query(uri, null, null, null, "title ASC");
1105 } catch (Exception e) {
1106 // Ignore
1107 }
1108
Dan Sandlerd5024042014-01-09 15:01:33 -05001109 // We already have a favorites database in the old provider
1110 if (c != null) {
1111 try {
1112 if (c.getCount() > 0) {
1113 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1114 final int intentIndex
1115 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1116 final int titleIndex
1117 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1118 final int iconTypeIndex
1119 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1120 final int iconIndex
1121 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1122 final int iconPackageIndex
1123 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1124 final int iconResourceIndex
1125 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1126 final int containerIndex
1127 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1128 final int itemTypeIndex
1129 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1130 final int screenIndex
1131 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1132 final int cellXIndex
1133 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1134 final int cellYIndex
1135 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1136 final int uriIndex
1137 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1138 final int displayModeIndex
1139 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
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) {
1187 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1188 continue;
1189 }
1190
Dan Sandlerd5024042014-01-09 15:01:33 -05001191 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001192 + c.getString(titleIndex) + "\" ("
1193 + cellX + "," + cellY + "@"
1194 + LauncherSettings.Favorites.containerToString(container)
1195 + "/" + screen
1196 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001197
1198 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001199
1200 final Intent intent;
1201 final ComponentName cn;
1202 try {
1203 intent = Intent.parseUri(intentStr, 0);
1204 } catch (URISyntaxException e) {
1205 // bogus intent?
1206 Launcher.addDumpLog(TAG,
1207 "skipping invalid intent uri", true);
1208 continue;
1209 }
1210
1211 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001212 if (TextUtils.isEmpty(intentStr)) {
1213 // no intent? no icon
1214 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1215 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001216 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001217 !LauncherModel.isValidPackageActivity(mContext, cn,
1218 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001219 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001220 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001221 "no longer exists.", true);
1222 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001223 } else if (container ==
1224 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1225 // Dedupe icons directly on the workspace
1226
Adam Cohen556f6132014-01-15 15:18:08 -08001227 // Canonicalize
1228 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001229 // does not, so we clear that out to keep them the same.
1230 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001231 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001232 int flags = intent.getFlags();
1233 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001234 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001235 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001236 if (seenIntents.contains(key)) {
1237 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001238 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001239 } else {
1240 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001241 }
1242 }
1243 }
1244
1245 ContentValues values = new ContentValues(c.getColumnCount());
1246 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1247 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1248 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1249 values.put(LauncherSettings.Favorites.ICON_TYPE,
1250 c.getInt(iconTypeIndex));
1251 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1252 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1253 c.getString(iconPackageIndex));
1254 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1255 c.getString(iconResourceIndex));
1256 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1257 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1258 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1259 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1260 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001261 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001262
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001263 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1264 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001265 }
1266
1267 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1268 // In a folder or in the hotseat, preserve position
1269 values.put(LauncherSettings.Favorites.SCREEN, screen);
1270 values.put(LauncherSettings.Favorites.CELLX, cellX);
1271 values.put(LauncherSettings.Favorites.CELLY, cellY);
1272 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001273 // For items contained directly on one of the workspace screen,
1274 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001275 }
1276
1277 values.put(LauncherSettings.Favorites.CONTAINER, container);
1278
Adam Cohen72960972014-01-15 18:13:55 -08001279 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1280 shortcuts.add(values);
1281 } else {
1282 folders.add(values);
1283 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001284 }
1285
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001286 // Now that we have all the hotseat icons, let's go through them left-right
1287 // and assign valid locations for them in the new hotseat
1288 final int N = hotseat.size();
1289 for (int idx=0; idx<N; idx++) {
1290 int hotseatX = hotseat.keyAt(idx);
1291 ContentValues values = hotseat.valueAt(idx);
1292
Adam Cohen2e6da152015-05-06 11:42:25 -07001293 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001294 // let's drop this in the next available hole in the hotseat
1295 while (++hotseatX < hotseatWidth) {
1296 if (hotseat.get(hotseatX) == null) {
1297 // found a spot! move it here
1298 values.put(LauncherSettings.Favorites.SCREEN,
1299 hotseatX);
1300 break;
1301 }
1302 }
1303 }
1304 if (hotseatX >= hotseatWidth) {
1305 // no room for you in the hotseat? it's off to the desktop with you
1306 values.put(LauncherSettings.Favorites.CONTAINER,
1307 Favorites.CONTAINER_DESKTOP);
1308 }
1309 }
1310
Adam Cohen72960972014-01-15 18:13:55 -08001311 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1312 // Folders first
1313 allItems.addAll(folders);
1314 // Then shortcuts
1315 allItems.addAll(shortcuts);
1316
1317 // Layout all the folders
1318 for (ContentValues values: allItems) {
1319 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1320 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1321 // Hotseat items and folder items have already had their
1322 // location information set. Nothing to be done here.
1323 continue;
1324 }
1325 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1326 values.put(LauncherSettings.Favorites.CELLX, curX);
1327 values.put(LauncherSettings.Favorites.CELLY, curY);
1328 curX = (curX + 1) % width;
1329 if (curX == 0) {
1330 curY = (curY + 1);
1331 }
1332 // Leave the last row of icons blank on every screen
1333 if (curY == height - 1) {
1334 curScreen = (int) generateNewScreenId();
1335 curY = 0;
1336 }
1337 }
1338
1339 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001340 db.beginTransaction();
1341 try {
Adam Cohen72960972014-01-15 18:13:55 -08001342 for (ContentValues row: allItems) {
1343 if (row == null) continue;
1344 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001345 < 0) {
1346 return;
1347 } else {
1348 count++;
1349 }
1350 }
1351 db.setTransactionSuccessful();
1352 } finally {
1353 db.endTransaction();
1354 }
1355 }
1356
1357 db.beginTransaction();
1358 try {
1359 for (i=0; i<=curScreen; i++) {
1360 final ContentValues values = new ContentValues();
1361 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1362 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1363 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1364 < 0) {
1365 return;
1366 }
1367 }
1368 db.setTransactionSuccessful();
1369 } finally {
1370 db.endTransaction();
1371 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001372
1373 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001374 }
1375 } finally {
1376 c.close();
1377 }
1378 }
1379
1380 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1381 + (curScreen+1) + " screens", true);
1382
1383 // ensure that new screens are created to hold these icons
1384 setFlagJustLoadedOldDb();
1385
1386 // Update max IDs; very important since we just grabbed IDs from another database
1387 mMaxItemId = initializeMaxItemId(db);
1388 mMaxScreenId = initializeMaxScreenId(db);
1389 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1390 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001391 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001392
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001393 /**
1394 * @return the max _id in the provided table.
1395 */
Adam Cohen091440a2015-03-18 14:16:05 -07001396 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001397 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1398 // get the result
1399 long id = -1;
1400 if (c != null && c.moveToNext()) {
1401 id = c.getLong(0);
1402 }
1403 if (c != null) {
1404 c.close();
1405 }
1406
1407 if (id == -1) {
1408 throw new RuntimeException("Error: could not query max id in " + table);
1409 }
1410
1411 return id;
1412 }
1413
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001414 static class SqlArguments {
1415 public final String table;
1416 public final String where;
1417 public final String[] args;
1418
1419 SqlArguments(Uri url, String where, String[] args) {
1420 if (url.getPathSegments().size() == 1) {
1421 this.table = url.getPathSegments().get(0);
1422 this.where = where;
1423 this.args = args;
1424 } else if (url.getPathSegments().size() != 2) {
1425 throw new IllegalArgumentException("Invalid URI: " + url);
1426 } else if (!TextUtils.isEmpty(where)) {
1427 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1428 } else {
1429 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001430 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001431 this.args = null;
1432 }
1433 }
1434
1435 SqlArguments(Uri url) {
1436 if (url.getPathSegments().size() == 1) {
1437 table = url.getPathSegments().get(0);
1438 where = null;
1439 args = null;
1440 } else {
1441 throw new IllegalArgumentException("Invalid URI: " + url);
1442 }
1443 }
1444 }
Adam Cohen72960972014-01-15 18:13:55 -08001445}