blob: ef79cf85e2cb183397ae8af0ce851a793478d8e7 [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,
Sunny Goyalf7258242015-10-19 16:59:07 -0700260 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
261 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700262 return result;
263 }
264 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
265 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700266 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyal7779d622015-06-11 16:18:39 -0700267 if (mListener != null) {
268 mListener.onSettingsChanged(arg, value);
269 }
270 Bundle result = new Bundle();
271 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
272 return result;
273 }
274 }
275 return null;
276 }
277
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700278 /**
279 * Deletes any empty folder from the DB.
280 * @return Ids of deleted folders.
281 */
282 public List<Long> deleteEmptyFolders() {
283 ArrayList<Long> folderIds = new ArrayList<Long>();
284 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
285 db.beginTransaction();
286 try {
287 // Select folders whose id do not match any container value.
288 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
289 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
290 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
291 LauncherSettings.Favorites.CONTAINER + " FROM "
292 + TABLE_FAVORITES + ")";
293 Cursor c = db.query(TABLE_FAVORITES,
294 new String[] {LauncherSettings.Favorites._ID},
295 selection, null, null, null, null);
296 while (c.moveToNext()) {
297 folderIds.add(c.getLong(0));
298 }
299 c.close();
300 if (folderIds.size() > 0) {
301 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
302 LauncherSettings.Favorites._ID, folderIds), null);
303 }
304 db.setTransactionSuccessful();
305 } catch (SQLException ex) {
306 Log.e(TAG, ex.getMessage(), ex);
307 folderIds.clear();
308 } finally {
309 db.endTransaction();
310 }
311 return folderIds;
312 }
313
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700314 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400315 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400316 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700317 if (mListener != null) {
318 mListener.onLauncherProviderChange();
319 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400320 }
321
Adam Cohen091440a2015-03-18 14:16:05 -0700322 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400323 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 }
325
Adam Cohendcd297f2013-06-18 13:13:40 -0700326 public long generateNewItemId() {
327 return mOpenHelper.generateNewItemId();
328 }
329
330 public long generateNewScreenId() {
331 return mOpenHelper.generateNewScreenId();
332 }
333
Brian Muramatsu5524b492012-10-02 16:55:54 -0700334 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700335 * Clears all the data for a fresh start.
336 */
337 synchronized public void createEmptyDB() {
338 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
339 }
340
Sunny Goyal33d44382014-10-16 09:24:19 -0700341 public void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700342 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700343 }
344
Sunny Goyal42de82f2014-09-26 22:09:29 -0700345 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700346 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700347 * 1) From the app restrictions
348 * 2) From a package provided by play store
349 * 3) From a partner configuration APK, already in the system image
350 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700351 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700352 synchronized public void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700353 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700354
Winson Chungc763c4e2013-07-19 13:49:06 -0700355 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500356 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200357
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700358 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
359 if (loader == null) {
360 loader = AutoInstallsLayout.get(getContext(),
361 mOpenHelper.mAppWidgetHost, mOpenHelper);
362 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700363 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700364 final Partner partner = Partner.get(getContext().getPackageManager());
365 if (partner != null && partner.hasDefaultLayout()) {
366 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700367 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700368 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700369 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700370 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
371 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700372 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700373 }
374 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700375
Sunny Goyal9d219682014-10-23 14:21:02 -0700376 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700377 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700378 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700379 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800380
381 // There might be some partially restored DB items, due to buggy restore logic in
382 // previous versions of launcher.
383 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700384 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700385 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
386 && usingExternallyProvidedLayout) {
387 // Unable to load external layout. Cleanup and load the internal layout.
388 createEmptyDB();
389 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
390 getDefaultLayoutParser());
391 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700392 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700393 }
394 }
395
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700396 /**
397 * Creates workspace loader from an XML resource listed in the app restrictions.
398 *
399 * @return the loader if the restrictions are set and the resource exists; null otherwise.
400 */
401 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
402 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
403 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700404 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700405 return null;
406 }
407
408 Context ctx = getContext();
409 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
410 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700411 if (bundle == null) {
412 return null;
413 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700414
Sunny Goyal35ca8732015-04-06 10:45:31 -0700415 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700416 if (packageName != null) {
417 try {
418 Resources targetResources = ctx.getPackageManager()
419 .getResourcesForApplication(packageName);
420 return AutoInstallsLayout.get(ctx, packageName, targetResources,
421 mOpenHelper.mAppWidgetHost, mOpenHelper);
422 } catch (NameNotFoundException e) {
423 Log.e(TAG, "Target package for restricted profile not found", e);
424 return null;
425 }
426 }
427 return null;
428 }
429
Sunny Goyal9d219682014-10-23 14:21:02 -0700430 private DefaultLayoutParser getDefaultLayoutParser() {
431 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700432 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700433 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
434 mOpenHelper, getContext().getResources(), defaultLayout);
435 }
436
Dan Sandlerd5024042014-01-09 15:01:33 -0500437 public void migrateLauncher2Shortcuts() {
438 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400439 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500440 }
441
Sunny Goyal08f72612015-01-05 13:41:43 -0800442 public void updateFolderItemsRank() {
443 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
444 }
445
Sunny Goyal5c97f512015-05-19 16:03:28 -0700446 public void convertShortcutsToLauncherActivities() {
447 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
448 }
449
450
Dan Sandlerd5024042014-01-09 15:01:33 -0500451 public void deleteDatabase() {
452 // Are you sure? (y/n)
453 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500454 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500455 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500456 if (dbFile.exists()) {
457 SQLiteDatabase.deleteDatabase(dbFile);
458 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500459 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700460 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500461 }
462
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700463 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800464 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700465 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700466 private long mMaxItemId = -1;
467 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468
Winson Chung0b560dd2014-01-21 13:00:26 -0800469 private boolean mNewDbCreated = false;
470
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700471 @Thunk LauncherProviderChangeListener mListener;
472
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800473 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100474 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800475 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700476 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700477
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700478 // Table creation sometimes fails silently, which leads to a crash loop.
479 // This way, we will try to create a table every time after crash, so the device
480 // would eventually be able to recover.
481 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
482 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
483 // This operation is a no-op if the table already exists.
484 addFavoritesTable(getWritableDatabase(), true);
485 addWorkspacesTable(getWritableDatabase(), true);
486 }
487
Winson Chung3d503fb2011-07-13 17:25:49 -0700488 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
489 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700490 if (mMaxItemId == -1) {
491 mMaxItemId = initializeMaxItemId(getWritableDatabase());
492 }
493 if (mMaxScreenId == -1) {
494 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700495 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 }
497
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700498 private boolean tableExists(String tableName) {
499 Cursor c = getReadableDatabase().query(
500 true, "sqlite_master", new String[] {"tbl_name"},
501 "tbl_name = ?", new String[] {tableName},
502 null, null, null, null, null);
503 try {
504 return c.getCount() > 0;
505 } finally {
506 c.close();
507 }
508 }
509
Winson Chung0b560dd2014-01-21 13:00:26 -0800510 public boolean wasNewDbCreated() {
511 return mNewDbCreated;
512 }
513
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800514 @Override
515 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800516 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700517
Adam Cohendcd297f2013-06-18 13:13:40 -0700518 mMaxItemId = 1;
519 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800520 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700521
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700522 addFavoritesTable(db, false);
523 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800524
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700525 // Database was just created, so wipe any previous widgets
526 if (mAppWidgetHost != null) {
527 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700528
529 /**
530 * Send notification that we've deleted the {@link AppWidgetHost},
531 * probably as part of the initial database creation. The receiver may
532 * want to re-call {@link AppWidgetHost#startListening()} to ensure
533 * callbacks are correctly set.
534 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700535 new MainThreadExecutor().execute(new Runnable() {
536
537 @Override
538 public void run() {
539 if (mListener != null) {
540 mListener.onAppWidgetHostReset();
541 }
542 }
543 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800544 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700545
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800546 // Fresh and clean launcher DB.
547 mMaxItemId = initializeMaxItemId(db);
548 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700549
550 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700551 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552 }
553
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700554 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
555 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
556 long userSerialNumber = userManager.getSerialNumberForUser(
557 UserHandleCompat.myUserHandle());
558 String ifNotExists = optional ? " IF NOT EXISTS " : "";
559
560 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
561 "_id INTEGER PRIMARY KEY," +
562 "title TEXT," +
563 "intent TEXT," +
564 "container INTEGER," +
565 "screen INTEGER," +
566 "cellX INTEGER," +
567 "cellY INTEGER," +
568 "spanX INTEGER," +
569 "spanY INTEGER," +
570 "itemType INTEGER," +
571 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
572 "isShortcut INTEGER," +
573 "iconType INTEGER," +
574 "iconPackage TEXT," +
575 "iconResource TEXT," +
576 "icon BLOB," +
577 "uri TEXT," +
578 "displayMode INTEGER," +
579 "appWidgetProvider TEXT," +
580 "modified INTEGER NOT NULL DEFAULT 0," +
581 "restored INTEGER NOT NULL DEFAULT 0," +
582 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
583 "rank INTEGER NOT NULL DEFAULT 0," +
584 "options INTEGER NOT NULL DEFAULT 0" +
585 ");");
586 }
587
588 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
589 String ifNotExists = optional ? " IF NOT EXISTS " : "";
590 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800591 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400592 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
593 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700594 ");");
595 }
596
Adam Cohen119285e2014-04-02 16:59:08 -0700597 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700598 // Delete items directly on the workspace who's screen id doesn't exist
599 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
600 // AND container = -100"
601 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
602 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700603 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700604 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
605 " AND " +
606 LauncherSettings.Favorites.CONTAINER + " = " +
607 LauncherSettings.Favorites.CONTAINER_DESKTOP;
608 db.execSQL(removeOrphanedDesktopItems);
609
610 // Delete items contained in folders which no longer exist (after above statement)
611 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
612 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
613 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
614 " WHERE " +
615 LauncherSettings.Favorites.CONTAINER + " <> " +
616 LauncherSettings.Favorites.CONTAINER_DESKTOP +
617 " AND "
618 + LauncherSettings.Favorites.CONTAINER + " <> " +
619 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
620 " AND "
621 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
622 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
623 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
624 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
625 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700626 }
627
Winson Chungc763c4e2013-07-19 13:49:06 -0700628 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700629 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700630 }
631
Winson Chungc763c4e2013-07-19 13:49:06 -0700632 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700633 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700634 }
635
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636 @Override
637 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700638 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800639 switch (oldVersion) {
640 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800641 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800642 case 12: {
643 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
644 // to persist workspace screens and their relative order.
645 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700646 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800647 }
648 case 13: {
649 db.beginTransaction();
650 try {
651 // Insert new column for holding widget provider name
652 db.execSQL("ALTER TABLE favorites " +
653 "ADD COLUMN appWidgetProvider TEXT;");
654 db.setTransactionSuccessful();
655 } catch (SQLException ex) {
656 Log.e(TAG, ex.getMessage(), ex);
657 // Old version remains, which means we wipe old data
658 break;
659 } finally {
660 db.endTransaction();
661 }
662 }
663 case 14: {
664 db.beginTransaction();
665 try {
666 // Insert new column for holding update timestamp
667 db.execSQL("ALTER TABLE favorites " +
668 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
669 db.execSQL("ALTER TABLE workspaceScreens " +
670 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
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 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700681 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800682 // Old version remains, which means we wipe old data
683 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800684 }
685 }
686 case 16: {
687 // We use the db version upgrade here to identify users who may not have seen
688 // clings yet (because they weren't available), but for whom the clings are now
689 // available (tablet users). Because one of the possible cling flows (migration)
690 // is very destructive (wipes out workspaces), we want to prevent this from showing
691 // until clear data. We do so by marking that the clings have been shown.
692 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
693 }
694 case 17: {
695 // No-op
696 }
697 case 18: {
698 // Due to a data loss bug, some users may have items associated with screen ids
699 // which no longer exist. Since this can cause other problems, and since the user
700 // will never see these items anyway, we use database upgrade as an opportunity to
701 // clean things up.
702 removeOrphanedItems(db);
703 }
704 case 19: {
705 // Add userId column
706 if (!addProfileColumn(db)) {
707 // Old version remains, which means we wipe old data
708 break;
709 }
710 }
711 case 20:
712 if (!updateFolderItemsRank(db, true)) {
713 break;
714 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800715 case 21:
716 // Recreate workspace table with screen id a primary key
717 if (!recreateWorkspaceTable(db)) {
718 break;
719 }
720 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700721 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
722 // Old version remains, which means we wipe old data
723 break;
724 }
725 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700726 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700727 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700728 case 24:
729 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700730 case 25:
731 convertShortcutsToLauncherActivities(db);
732 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 // DB Upgraded successfully
734 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400735 }
736 }
737
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 // DB was not upgraded
739 Log.w(TAG, "Destroying all old data.");
740 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800742
Adam Cohen9b1d0622014-05-21 19:01:57 -0700743 @Override
744 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
745 // This shouldn't happen -- throw our hands up in the air and start over.
746 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
747 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700748 createEmptyDB(db);
749 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700750
Sunny Goyal42de82f2014-09-26 22:09:29 -0700751 /**
752 * Clears all the data for a fresh start.
753 */
754 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700755 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
756 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
757 onCreate(db);
758 }
759
Sunny Goyald2f38192015-02-25 10:46:34 -0800760 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700761 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
762 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
763 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700764 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700765 db.beginTransaction();
766 Cursor c = null;
767 SQLiteStatement updateStmt = null;
768
769 try {
770 // Only consider the primary user as other users can't have a shortcut.
771 long userSerial = UserManagerCompat.getInstance(mContext)
772 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
773 c = db.query(TABLE_FAVORITES, new String[] {
774 Favorites._ID,
775 Favorites.INTENT,
776 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
777 null, null, null, null);
778
779 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
780 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
781
782 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
783 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
784
785 while (c.moveToNext()) {
786 String intentDescription = c.getString(intentIndex);
787 Intent intent;
788 try {
789 intent = Intent.parseUri(intentDescription, 0);
790 } catch (URISyntaxException e) {
791 Log.e(TAG, "Unable to parse intent", e);
792 continue;
793 }
794
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700795 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700796 continue;
797 }
798
799 long id = c.getLong(idIndex);
800 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700801 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700802 }
803 db.setTransactionSuccessful();
804 } catch (SQLException ex) {
805 Log.w(TAG, "Error deduping shortcuts", ex);
806 } finally {
807 db.endTransaction();
808 if (c != null) {
809 c.close();
810 }
811 if (updateStmt != null) {
812 updateStmt.close();
813 }
814 }
815 }
816
817 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800818 * Recreates workspace table and migrates data to the new table.
819 */
820 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
821 db.beginTransaction();
822 try {
823 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
824 new String[] {LauncherSettings.WorkspaceScreens._ID},
825 null, null, null, null,
826 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
827 ArrayList<Long> sortedIDs = new ArrayList<Long>();
828 long maxId = 0;
829 try {
830 while (c.moveToNext()) {
831 Long id = c.getLong(0);
832 if (!sortedIDs.contains(id)) {
833 sortedIDs.add(id);
834 maxId = Math.max(maxId, id);
835 }
836 }
837 } finally {
838 c.close();
839 }
840
841 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700842 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800843
844 // Add all screen ids back
845 int total = sortedIDs.size();
846 for (int i = 0; i < total; i++) {
847 ContentValues values = new ContentValues();
848 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
849 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
850 addModifiedTime(values);
851 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
852 }
853 db.setTransactionSuccessful();
854 mMaxScreenId = maxId;
855 } catch (SQLException ex) {
856 // Old version remains, which means we wipe old data
857 Log.e(TAG, ex.getMessage(), ex);
858 return false;
859 } finally {
860 db.endTransaction();
861 }
862 return true;
863 }
864
Adam Cohen091440a2015-03-18 14:16:05 -0700865 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800866 db.beginTransaction();
867 try {
868 if (addRankColumn) {
869 // Insert new column for holding rank
870 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
871 }
872
873 // Get a map for folder ID to folder width
874 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
875 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
876 + " GROUP BY container;",
877 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
878
879 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800880 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
881 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800882 new Object[] {c.getLong(1) + 1, c.getLong(0)});
883 }
884
885 c.close();
886 db.setTransactionSuccessful();
887 } catch (SQLException ex) {
888 // Old version remains, which means we wipe old data
889 Log.e(TAG, ex.getMessage(), ex);
890 return false;
891 } finally {
892 db.endTransaction();
893 }
894 return true;
895 }
896
Kenny Guyed131872014-04-30 03:02:21 +0100897 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700898 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
899 // Default to the serial number of this user, for older
900 // shortcuts.
901 long userSerialNumber = userManager.getSerialNumberForUser(
902 UserHandleCompat.myUserHandle());
903 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
904 }
905
906 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100907 db.beginTransaction();
908 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700909 db.execSQL("ALTER TABLE favorites ADD COLUMN "
910 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100911 db.setTransactionSuccessful();
912 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100913 Log.e(TAG, ex.getMessage(), ex);
914 return false;
915 } finally {
916 db.endTransaction();
917 }
918 return true;
919 }
920
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700921 // Generates a new ID to use for an object in your database. This method should be only
922 // called from the main UI thread. As an exception, we do call it when we call the
923 // constructor from the worker thread; however, this doesn't extend until after the
924 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
925 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700926 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700927 public long generateNewItemId() {
928 if (mMaxItemId < 0) {
929 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700930 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700931 mMaxItemId += 1;
932 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700933 }
934
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700935 @Override
936 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
937 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
938 }
939
Chris Wren5dee7af2013-12-20 17:22:11 -0500940 public void checkId(String table, ContentValues values) {
941 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
942 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
943 mMaxScreenId = Math.max(id, mMaxScreenId);
944 } else {
945 mMaxItemId = Math.max(id, mMaxItemId);
946 }
947 }
948
Adam Cohendcd297f2013-06-18 13:13:40 -0700949 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800950 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700951 }
952
953 // Generates a new ID to use for an workspace screen in your database. This method
954 // should be only called from the main UI thread. As an exception, we do call it when we
955 // call the constructor from the worker thread; however, this doesn't extend until after the
956 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
957 // after that point
958 public long generateNewScreenId() {
959 if (mMaxScreenId < 0) {
960 throw new RuntimeException("Error: max screen id was not initialized");
961 }
962 mMaxScreenId += 1;
963 return mMaxScreenId;
964 }
965
Adam Cohendcd297f2013-06-18 13:13:40 -0700966 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800967 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800968 }
969
Adam Cohen091440a2015-03-18 14:16:05 -0700970 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700971 // 1. Ensure that externally added items have a valid item id
972 long id = generateNewItemId();
973 values.put(LauncherSettings.Favorites._ID, id);
974
975 // 2. In the case of an app widget, and if no app widget id is specified, we
976 // attempt allocate and bind the widget.
977 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
978 if (itemType != null &&
979 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
980 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
981
982 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
983 ComponentName cn = ComponentName.unflattenFromString(
984 values.getAsString(Favorites.APPWIDGET_PROVIDER));
985
986 if (cn != null) {
987 try {
988 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700989 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700990 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700991 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700992 }
993 } catch (RuntimeException e) {
994 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700995 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700996 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700997 } else {
998 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700999 }
1000 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001001
1002 // Add screen id if not present
1003 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1004 if (!addScreenIdIfNecessary(screenId)) {
1005 return false;
1006 }
Adam Cohena043fa82014-07-23 14:49:38 -07001007 return true;
1008 }
1009
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001010 // Returns true of screen id exists, or if successfully added
1011 private boolean addScreenIdIfNecessary(long screenId) {
1012 if (!hasScreenId(screenId)) {
1013 int rank = getMaxScreenRank() + 1;
1014
1015 ContentValues v = new ContentValues();
1016 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1017 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1018 if (dbInsertAndCheck(this, getWritableDatabase(),
1019 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1020 return false;
1021 }
1022 }
1023 return true;
1024 }
1025
1026 private boolean hasScreenId(long screenId) {
1027 SQLiteDatabase db = getWritableDatabase();
1028 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1029 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1030 if (c != null) {
1031 int count = c.getCount();
1032 c.close();
1033 return count > 0;
1034 } else {
1035 return false;
1036 }
1037 }
1038
1039 private int getMaxScreenRank() {
1040 SQLiteDatabase db = getWritableDatabase();
1041 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1042 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1043
1044 // get the result
1045 final int maxRankIndex = 0;
1046 int rank = -1;
1047 if (c != null && c.moveToNext()) {
1048 rank = c.getInt(maxRankIndex);
1049 }
1050 if (c != null) {
1051 c.close();
1052 }
1053
1054 return rank;
1055 }
1056
Adam Cohen091440a2015-03-18 14:16:05 -07001057 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001058 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001059 // TODO: Use multiple loaders with fall-back and transaction.
1060 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001061
1062 // Add the screens specified by the items above
1063 Collections.sort(screenIds);
1064 int rank = 0;
1065 ContentValues values = new ContentValues();
1066 for (Long id : screenIds) {
1067 values.clear();
1068 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1069 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1070 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1071 throw new RuntimeException("Failed initialize screen table"
1072 + "from default layout");
1073 }
1074 rank++;
1075 }
1076
1077 // Ensure that the max ids are initialized
1078 mMaxItemId = initializeMaxItemId(db);
1079 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001080
Adam Cohen71483f42014-05-15 14:04:01 -07001081 return count;
1082 }
1083
Adam Cohen091440a2015-03-18 14:16:05 -07001084 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001085 final ContentResolver resolver = mContext.getContentResolver();
1086 Cursor c = null;
1087 int count = 0;
1088 int curScreen = 0;
1089
1090 try {
1091 c = resolver.query(uri, null, null, null, "title ASC");
1092 } catch (Exception e) {
1093 // Ignore
1094 }
1095
Dan Sandlerd5024042014-01-09 15:01:33 -05001096 // We already have a favorites database in the old provider
1097 if (c != null) {
1098 try {
1099 if (c.getCount() > 0) {
1100 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1101 final int intentIndex
1102 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1103 final int titleIndex
1104 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1105 final int iconTypeIndex
1106 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1107 final int iconIndex
1108 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1109 final int iconPackageIndex
1110 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1111 final int iconResourceIndex
1112 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1113 final int containerIndex
1114 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1115 final int itemTypeIndex
1116 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1117 final int screenIndex
1118 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1119 final int cellXIndex
1120 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1121 final int cellYIndex
1122 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1123 final int uriIndex
1124 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1125 final int displayModeIndex
1126 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001127 final int profileIndex
1128 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001129
1130 int i = 0;
1131 int curX = 0;
1132 int curY = 0;
1133
1134 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001135 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1136 final int width = (int) profile.numColumns;
1137 final int height = (int) profile.numRows;
1138 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001139
1140 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1141
Adam Cohen72960972014-01-15 18:13:55 -08001142 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1143 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001144 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001145
1146 while (c.moveToNext()) {
1147 final int itemType = c.getInt(itemTypeIndex);
1148 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1149 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1150 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1151 continue;
1152 }
1153
1154 final int cellX = c.getInt(cellXIndex);
1155 final int cellY = c.getInt(cellYIndex);
1156 final int screen = c.getInt(screenIndex);
1157 int container = c.getInt(containerIndex);
1158 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001159
1160 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1161 UserHandleCompat userHandle;
1162 final long userSerialNumber;
1163 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1164 userSerialNumber = c.getInt(profileIndex);
1165 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1166 } else {
1167 // Default to the serial number of this user, for older
1168 // shortcuts.
1169 userHandle = UserHandleCompat.myUserHandle();
1170 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1171 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001172
1173 if (userHandle == null) {
1174 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1175 continue;
1176 }
1177
Dan Sandlerd5024042014-01-09 15:01:33 -05001178 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001179 + c.getString(titleIndex) + "\" ("
1180 + cellX + "," + cellY + "@"
1181 + LauncherSettings.Favorites.containerToString(container)
1182 + "/" + screen
1183 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001184
1185 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001186
1187 final Intent intent;
1188 final ComponentName cn;
1189 try {
1190 intent = Intent.parseUri(intentStr, 0);
1191 } catch (URISyntaxException e) {
1192 // bogus intent?
1193 Launcher.addDumpLog(TAG,
1194 "skipping invalid intent uri", true);
1195 continue;
1196 }
1197
1198 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001199 if (TextUtils.isEmpty(intentStr)) {
1200 // no intent? no icon
1201 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1202 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001203 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001204 !LauncherModel.isValidPackageActivity(mContext, cn,
1205 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001206 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001207 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001208 "no longer exists.", true);
1209 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001210 } else if (container ==
1211 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1212 // Dedupe icons directly on the workspace
1213
Adam Cohen556f6132014-01-15 15:18:08 -08001214 // Canonicalize
1215 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001216 // does not, so we clear that out to keep them the same.
1217 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001218 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001219 int flags = intent.getFlags();
1220 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001221 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001222 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001223 if (seenIntents.contains(key)) {
1224 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001225 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001226 } else {
1227 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001228 }
1229 }
1230 }
1231
1232 ContentValues values = new ContentValues(c.getColumnCount());
1233 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1234 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1235 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1236 values.put(LauncherSettings.Favorites.ICON_TYPE,
1237 c.getInt(iconTypeIndex));
1238 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1239 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1240 c.getString(iconPackageIndex));
1241 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1242 c.getString(iconResourceIndex));
1243 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1244 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1245 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1246 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1247 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001248 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001249
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001250 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1251 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001252 }
1253
1254 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1255 // In a folder or in the hotseat, preserve position
1256 values.put(LauncherSettings.Favorites.SCREEN, screen);
1257 values.put(LauncherSettings.Favorites.CELLX, cellX);
1258 values.put(LauncherSettings.Favorites.CELLY, cellY);
1259 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001260 // For items contained directly on one of the workspace screen,
1261 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001262 }
1263
1264 values.put(LauncherSettings.Favorites.CONTAINER, container);
1265
Adam Cohen72960972014-01-15 18:13:55 -08001266 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1267 shortcuts.add(values);
1268 } else {
1269 folders.add(values);
1270 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001271 }
1272
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001273 // Now that we have all the hotseat icons, let's go through them left-right
1274 // and assign valid locations for them in the new hotseat
1275 final int N = hotseat.size();
1276 for (int idx=0; idx<N; idx++) {
1277 int hotseatX = hotseat.keyAt(idx);
1278 ContentValues values = hotseat.valueAt(idx);
1279
Adam Cohen2e6da152015-05-06 11:42:25 -07001280 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001281 // let's drop this in the next available hole in the hotseat
1282 while (++hotseatX < hotseatWidth) {
1283 if (hotseat.get(hotseatX) == null) {
1284 // found a spot! move it here
1285 values.put(LauncherSettings.Favorites.SCREEN,
1286 hotseatX);
1287 break;
1288 }
1289 }
1290 }
1291 if (hotseatX >= hotseatWidth) {
1292 // no room for you in the hotseat? it's off to the desktop with you
1293 values.put(LauncherSettings.Favorites.CONTAINER,
1294 Favorites.CONTAINER_DESKTOP);
1295 }
1296 }
1297
Adam Cohen72960972014-01-15 18:13:55 -08001298 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1299 // Folders first
1300 allItems.addAll(folders);
1301 // Then shortcuts
1302 allItems.addAll(shortcuts);
1303
1304 // Layout all the folders
1305 for (ContentValues values: allItems) {
1306 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1307 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1308 // Hotseat items and folder items have already had their
1309 // location information set. Nothing to be done here.
1310 continue;
1311 }
1312 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1313 values.put(LauncherSettings.Favorites.CELLX, curX);
1314 values.put(LauncherSettings.Favorites.CELLY, curY);
1315 curX = (curX + 1) % width;
1316 if (curX == 0) {
1317 curY = (curY + 1);
1318 }
1319 // Leave the last row of icons blank on every screen
1320 if (curY == height - 1) {
1321 curScreen = (int) generateNewScreenId();
1322 curY = 0;
1323 }
1324 }
1325
1326 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001327 db.beginTransaction();
1328 try {
Adam Cohen72960972014-01-15 18:13:55 -08001329 for (ContentValues row: allItems) {
1330 if (row == null) continue;
1331 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001332 < 0) {
1333 return;
1334 } else {
1335 count++;
1336 }
1337 }
1338 db.setTransactionSuccessful();
1339 } finally {
1340 db.endTransaction();
1341 }
1342 }
1343
1344 db.beginTransaction();
1345 try {
1346 for (i=0; i<=curScreen; i++) {
1347 final ContentValues values = new ContentValues();
1348 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1349 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1350 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1351 < 0) {
1352 return;
1353 }
1354 }
1355 db.setTransactionSuccessful();
1356 } finally {
1357 db.endTransaction();
1358 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001359
1360 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001361 }
1362 } finally {
1363 c.close();
1364 }
1365 }
1366
1367 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1368 + (curScreen+1) + " screens", true);
1369
1370 // ensure that new screens are created to hold these icons
1371 setFlagJustLoadedOldDb();
1372
1373 // Update max IDs; very important since we just grabbed IDs from another database
1374 mMaxItemId = initializeMaxItemId(db);
1375 mMaxScreenId = initializeMaxScreenId(db);
1376 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1377 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001378 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001379
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001380 /**
1381 * @return the max _id in the provided table.
1382 */
Adam Cohen091440a2015-03-18 14:16:05 -07001383 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001384 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1385 // get the result
1386 long id = -1;
1387 if (c != null && c.moveToNext()) {
1388 id = c.getLong(0);
1389 }
1390 if (c != null) {
1391 c.close();
1392 }
1393
1394 if (id == -1) {
1395 throw new RuntimeException("Error: could not query max id in " + table);
1396 }
1397
1398 return id;
1399 }
1400
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001401 static class SqlArguments {
1402 public final String table;
1403 public final String where;
1404 public final String[] args;
1405
1406 SqlArguments(Uri url, String where, String[] args) {
1407 if (url.getPathSegments().size() == 1) {
1408 this.table = url.getPathSegments().get(0);
1409 this.where = where;
1410 this.args = args;
1411 } else if (url.getPathSegments().size() != 2) {
1412 throw new IllegalArgumentException("Invalid URI: " + url);
1413 } else if (!TextUtils.isEmpty(where)) {
1414 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1415 } else {
1416 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001417 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001418 this.args = null;
1419 }
1420 }
1421
1422 SqlArguments(Uri url) {
1423 if (url.getPathSegments().size() == 1) {
1424 table = url.getPathSegments().get(0);
1425 where = null;
1426 args = null;
1427 } else {
1428 throw new IllegalArgumentException("Invalid URI: " + url);
1429 }
1430 }
1431 }
Adam Cohen72960972014-01-15 18:13:55 -08001432}