blob: 4760930321d1583a62f578e40f1e575b31faa399 [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
Mike Cleronb87bd162009-10-30 16:36:56 -070060import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070061import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070062import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050063import java.util.HashSet;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070064import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070067 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Sunny Goyale5bb7052015-07-27 14:36:07 -070072 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070073
Sunny Goyal18b640c2015-04-17 09:24:01 -070074 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
75 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080076 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Sunny Goyal383c5072015-06-12 21:18:53 -070080 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070081 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
83 @Override
84 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040085 final Context context = getContext();
Sunny Goyal7bce5f72015-11-24 11:40:40 -080086 // The content provider exists for the entire duration of the launcher main process and
87 // is the first component to get created. Initializing application context here ensures
88 // that LauncherAppState always exists in the main process.
89 LauncherAppState.setApplicationContext(context.getApplicationContext());
Nilesh Agrawala258f812015-01-26 14:07:29 -080090 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080092 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040093 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 return true;
95 }
96
Winson Chung0b560dd2014-01-21 13:00:26 -080097 public boolean wasNewDbCreated() {
98 return mOpenHelper.wasNewDbCreated();
99 }
100
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
102 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700103 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700104 }
105
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106 @Override
107 public String getType(Uri uri) {
108 SqlArguments args = new SqlArguments(uri, null, null);
109 if (TextUtils.isEmpty(args.where)) {
110 return "vnd.android.cursor.dir/" + args.table;
111 } else {
112 return "vnd.android.cursor.item/" + args.table;
113 }
114 }
115
116 @Override
117 public Cursor query(Uri uri, String[] projection, String selection,
118 String[] selectionArgs, String sortOrder) {
119
120 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
121 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
122 qb.setTables(args.table);
123
Romain Guy73b979d2009-06-09 12:57:21 -0700124 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
126 result.setNotificationUri(getContext().getContentResolver(), uri);
127
128 return result;
129 }
130
Adam Cohen091440a2015-03-18 14:16:05 -0700131 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700132 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500133 if (values == null) {
134 throw new RuntimeException("Error: attempting to insert null values");
135 }
Adam Cohen71483f42014-05-15 14:04:01 -0700136 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 throw new RuntimeException("Error: attempting to add item without specifying an id");
138 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500139 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 return db.insert(table, nullColumnHack, values);
141 }
142
Sunny Goyald1064182015-08-13 12:08:30 -0700143 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700144 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700145 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
146 if (app != null) {
147 app.reloadWorkspace();
148 }
149 }
150 }
151
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 @Override
153 public Uri insert(Uri uri, ContentValues initialValues) {
154 SqlArguments args = new SqlArguments(uri);
155
Sunny Goyald1064182015-08-13 12:08:30 -0700156 // In very limited cases, we support system|signature permission apps to modify the db.
157 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700158 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
159 return null;
160 }
161 }
162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400164 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800166 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
168 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700169 notifyListeners();
170
Sunny Goyalc74e4192015-09-08 14:01:03 -0700171 if (Utilities.ATLEAST_MARSHMALLOW) {
172 reloadLauncherIfExternal();
173 } else {
174 // Deprecated behavior to support legacy devices which rely on provider callbacks.
175 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
176 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
177 app.reloadWorkspace();
178 }
179
180 String notify = uri.getQueryParameter("notify");
181 if (notify == null || "true".equals(notify)) {
182 getContext().getContentResolver().notifyChange(uri, null);
183 }
184 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185 return uri;
186 }
187
Adam Cohena043fa82014-07-23 14:49:38 -0700188
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 @Override
190 public int bulkInsert(Uri uri, ContentValues[] values) {
191 SqlArguments args = new SqlArguments(uri);
192
193 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
194 db.beginTransaction();
195 try {
196 int numValues = values.length;
197 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400198 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700199 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
200 return 0;
201 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 }
203 db.setTransactionSuccessful();
204 } finally {
205 db.endTransaction();
206 }
207
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700208 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700209 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210 return values.length;
211 }
212
213 @Override
Yura085c8532014-02-11 15:15:29 +0000214 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
215 throws OperationApplicationException {
216 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
217 db.beginTransaction();
218 try {
219 ContentProviderResult[] result = super.applyBatch(operations);
220 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700221 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000222 return result;
223 } finally {
224 db.endTransaction();
225 }
226 }
227
228 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 public int delete(Uri uri, String selection, String[] selectionArgs) {
230 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
231
232 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
233 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700234 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235
Sunny Goyald1064182015-08-13 12:08:30 -0700236 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237 return count;
238 }
239
240 @Override
241 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
242 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
243
Chris Wren1ada10d2013-09-13 18:01:38 -0400244 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800245 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
246 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700247 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248
Sunny Goyald1064182015-08-13 12:08:30 -0700249 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 return count;
251 }
252
Sunny Goyal7779d622015-06-11 16:18:39 -0700253 @Override
254 public Bundle call(String method, String arg, Bundle extras) {
255 if (Binder.getCallingUid() != Process.myUid()) {
256 return null;
257 }
258
259 switch (method) {
260 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
261 Bundle result = new Bundle();
262 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700263 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
264 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700265 return result;
266 }
267 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
268 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700269 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyal7779d622015-06-11 16:18:39 -0700270 if (mListener != null) {
271 mListener.onSettingsChanged(arg, value);
272 }
Sunny Goyalb171e562016-01-21 16:41:54 -0800273 if (extras.getBoolean(LauncherSettings.Settings.NOTIFY_BACKUP)) {
274 LauncherBackupAgentHelper.dataChanged(getContext());
275 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700276 Bundle result = new Bundle();
277 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
278 return result;
279 }
280 }
281 return null;
282 }
283
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700284 /**
285 * Deletes any empty folder from the DB.
286 * @return Ids of deleted folders.
287 */
288 public List<Long> deleteEmptyFolders() {
289 ArrayList<Long> folderIds = new ArrayList<Long>();
290 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
291 db.beginTransaction();
292 try {
293 // Select folders whose id do not match any container value.
294 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
295 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
296 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
297 LauncherSettings.Favorites.CONTAINER + " FROM "
298 + TABLE_FAVORITES + ")";
299 Cursor c = db.query(TABLE_FAVORITES,
300 new String[] {LauncherSettings.Favorites._ID},
301 selection, null, null, null, null);
302 while (c.moveToNext()) {
303 folderIds.add(c.getLong(0));
304 }
305 c.close();
306 if (folderIds.size() > 0) {
307 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
308 LauncherSettings.Favorites._ID, folderIds), null);
309 }
310 db.setTransactionSuccessful();
311 } catch (SQLException ex) {
312 Log.e(TAG, ex.getMessage(), ex);
313 folderIds.clear();
314 } finally {
315 db.endTransaction();
316 }
317 return folderIds;
318 }
319
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700320 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400321 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400322 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700323 if (mListener != null) {
324 mListener.onLauncherProviderChange();
325 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400326 }
327
Adam Cohen091440a2015-03-18 14:16:05 -0700328 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400329 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 }
331
Adam Cohendcd297f2013-06-18 13:13:40 -0700332 public long generateNewItemId() {
333 return mOpenHelper.generateNewItemId();
334 }
335
336 public long generateNewScreenId() {
337 return mOpenHelper.generateNewScreenId();
338 }
339
Brian Muramatsu5524b492012-10-02 16:55:54 -0700340 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700341 * Clears all the data for a fresh start.
342 */
343 synchronized public void createEmptyDB() {
344 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
345 }
346
Sunny Goyal33d44382014-10-16 09:24:19 -0700347 public void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700348 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700349 }
350
Sunny Goyal42de82f2014-09-26 22:09:29 -0700351 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700352 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700353 * 1) From the app restrictions
354 * 2) From a package provided by play store
355 * 3) From a partner configuration APK, already in the system image
356 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700357 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700358 synchronized public void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700359 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700360
Winson Chungc763c4e2013-07-19 13:49:06 -0700361 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500362 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200363
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700364 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
365 if (loader == null) {
366 loader = AutoInstallsLayout.get(getContext(),
367 mOpenHelper.mAppWidgetHost, mOpenHelper);
368 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700369 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700370 final Partner partner = Partner.get(getContext().getPackageManager());
371 if (partner != null && partner.hasDefaultLayout()) {
372 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700373 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700374 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700375 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700376 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
377 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700378 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700379 }
380 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700381
Sunny Goyal9d219682014-10-23 14:21:02 -0700382 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700383 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700384 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700385 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800386
387 // There might be some partially restored DB items, due to buggy restore logic in
388 // previous versions of launcher.
389 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700390 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700391 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
392 && usingExternallyProvidedLayout) {
393 // Unable to load external layout. Cleanup and load the internal layout.
394 createEmptyDB();
395 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
396 getDefaultLayoutParser());
397 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700398 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700399 }
400 }
401
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700402 /**
403 * Creates workspace loader from an XML resource listed in the app restrictions.
404 *
405 * @return the loader if the restrictions are set and the resource exists; null otherwise.
406 */
407 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
408 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
409 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700410 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700411 return null;
412 }
413
414 Context ctx = getContext();
415 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
416 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700417 if (bundle == null) {
418 return null;
419 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700420
Sunny Goyal35ca8732015-04-06 10:45:31 -0700421 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700422 if (packageName != null) {
423 try {
424 Resources targetResources = ctx.getPackageManager()
425 .getResourcesForApplication(packageName);
426 return AutoInstallsLayout.get(ctx, packageName, targetResources,
427 mOpenHelper.mAppWidgetHost, mOpenHelper);
428 } catch (NameNotFoundException e) {
429 Log.e(TAG, "Target package for restricted profile not found", e);
430 return null;
431 }
432 }
433 return null;
434 }
435
Sunny Goyal9d219682014-10-23 14:21:02 -0700436 private DefaultLayoutParser getDefaultLayoutParser() {
437 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700438 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700439 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
440 mOpenHelper, getContext().getResources(), defaultLayout);
441 }
442
Dan Sandlerd5024042014-01-09 15:01:33 -0500443 public void migrateLauncher2Shortcuts() {
444 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400445 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500446 }
447
Sunny Goyal08f72612015-01-05 13:41:43 -0800448 public void updateFolderItemsRank() {
449 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
450 }
451
Sunny Goyal5c97f512015-05-19 16:03:28 -0700452 public void convertShortcutsToLauncherActivities() {
453 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
454 }
455
456
Dan Sandlerd5024042014-01-09 15:01:33 -0500457 public void deleteDatabase() {
458 // Are you sure? (y/n)
Sunny Goyal33f90e72015-11-30 10:59:35 -0800459 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Dan Sandlerd5024042014-01-09 15:01:33 -0500460 }
461
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700462 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700464 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700465 private long mMaxItemId = -1;
466 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800467
Winson Chung0b560dd2014-01-21 13:00:26 -0800468 private boolean mNewDbCreated = false;
469
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700470 @Thunk LauncherProviderChangeListener mListener;
471
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100473 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700475 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700476
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700477 // Table creation sometimes fails silently, which leads to a crash loop.
478 // This way, we will try to create a table every time after crash, so the device
479 // would eventually be able to recover.
480 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
481 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
482 // This operation is a no-op if the table already exists.
483 addFavoritesTable(getWritableDatabase(), true);
484 addWorkspacesTable(getWritableDatabase(), true);
485 }
486
Winson Chung3d503fb2011-07-13 17:25:49 -0700487 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
488 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700489 if (mMaxItemId == -1) {
490 mMaxItemId = initializeMaxItemId(getWritableDatabase());
491 }
492 if (mMaxScreenId == -1) {
493 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700494 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800495 }
496
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700497 private boolean tableExists(String tableName) {
498 Cursor c = getReadableDatabase().query(
499 true, "sqlite_master", new String[] {"tbl_name"},
500 "tbl_name = ?", new String[] {tableName},
501 null, null, null, null, null);
502 try {
503 return c.getCount() > 0;
504 } finally {
505 c.close();
506 }
507 }
508
Winson Chung0b560dd2014-01-21 13:00:26 -0800509 public boolean wasNewDbCreated() {
510 return mNewDbCreated;
511 }
512
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800513 @Override
514 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800515 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700516
Adam Cohendcd297f2013-06-18 13:13:40 -0700517 mMaxItemId = 1;
518 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800519 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700520
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700521 addFavoritesTable(db, false);
522 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800523
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700524 // Database was just created, so wipe any previous widgets
525 if (mAppWidgetHost != null) {
526 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700527
528 /**
529 * Send notification that we've deleted the {@link AppWidgetHost},
530 * probably as part of the initial database creation. The receiver may
531 * want to re-call {@link AppWidgetHost#startListening()} to ensure
532 * callbacks are correctly set.
533 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700534 new MainThreadExecutor().execute(new Runnable() {
535
536 @Override
537 public void run() {
538 if (mListener != null) {
539 mListener.onAppWidgetHostReset();
540 }
541 }
542 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800543 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700544
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800545 // Fresh and clean launcher DB.
546 mMaxItemId = initializeMaxItemId(db);
547 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700548
549 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700550 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551 }
552
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700553 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
554 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
555 long userSerialNumber = userManager.getSerialNumberForUser(
556 UserHandleCompat.myUserHandle());
557 String ifNotExists = optional ? " IF NOT EXISTS " : "";
558
559 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
560 "_id INTEGER PRIMARY KEY," +
561 "title TEXT," +
562 "intent TEXT," +
563 "container INTEGER," +
564 "screen INTEGER," +
565 "cellX INTEGER," +
566 "cellY INTEGER," +
567 "spanX INTEGER," +
568 "spanY INTEGER," +
569 "itemType INTEGER," +
570 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
571 "isShortcut INTEGER," +
572 "iconType INTEGER," +
573 "iconPackage TEXT," +
574 "iconResource TEXT," +
575 "icon BLOB," +
576 "uri TEXT," +
577 "displayMode INTEGER," +
578 "appWidgetProvider TEXT," +
579 "modified INTEGER NOT NULL DEFAULT 0," +
580 "restored INTEGER NOT NULL DEFAULT 0," +
581 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
582 "rank INTEGER NOT NULL DEFAULT 0," +
583 "options INTEGER NOT NULL DEFAULT 0" +
584 ");");
585 }
586
587 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
588 String ifNotExists = optional ? " IF NOT EXISTS " : "";
589 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800590 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400591 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
592 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700593 ");");
594 }
595
Adam Cohen119285e2014-04-02 16:59:08 -0700596 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700597 // Delete items directly on the workspace who's screen id doesn't exist
598 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
599 // AND container = -100"
600 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
601 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700602 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700603 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
604 " AND " +
605 LauncherSettings.Favorites.CONTAINER + " = " +
606 LauncherSettings.Favorites.CONTAINER_DESKTOP;
607 db.execSQL(removeOrphanedDesktopItems);
608
609 // Delete items contained in folders which no longer exist (after above statement)
610 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
611 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
612 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
613 " WHERE " +
614 LauncherSettings.Favorites.CONTAINER + " <> " +
615 LauncherSettings.Favorites.CONTAINER_DESKTOP +
616 " AND "
617 + LauncherSettings.Favorites.CONTAINER + " <> " +
618 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
619 " AND "
620 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
621 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
622 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
623 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
624 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700625 }
626
Winson Chungc763c4e2013-07-19 13:49:06 -0700627 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700628 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700629 }
630
Winson Chungc763c4e2013-07-19 13:49:06 -0700631 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700632 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700633 }
634
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 @Override
636 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700637 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800638 switch (oldVersion) {
639 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800640 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800641 case 12: {
642 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
643 // to persist workspace screens and their relative order.
644 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700645 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800646 }
647 case 13: {
648 db.beginTransaction();
649 try {
650 // Insert new column for holding widget provider name
651 db.execSQL("ALTER TABLE favorites " +
652 "ADD COLUMN appWidgetProvider TEXT;");
653 db.setTransactionSuccessful();
654 } catch (SQLException ex) {
655 Log.e(TAG, ex.getMessage(), ex);
656 // Old version remains, which means we wipe old data
657 break;
658 } finally {
659 db.endTransaction();
660 }
661 }
662 case 14: {
663 db.beginTransaction();
664 try {
665 // Insert new column for holding update timestamp
666 db.execSQL("ALTER TABLE favorites " +
667 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
668 db.execSQL("ALTER TABLE workspaceScreens " +
669 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
670 db.setTransactionSuccessful();
671 } catch (SQLException ex) {
672 Log.e(TAG, ex.getMessage(), ex);
673 // Old version remains, which means we wipe old data
674 break;
675 } finally {
676 db.endTransaction();
677 }
678 }
679 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700680 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 // Old version remains, which means we wipe old data
682 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800683 }
684 }
685 case 16: {
686 // We use the db version upgrade here to identify users who may not have seen
687 // clings yet (because they weren't available), but for whom the clings are now
688 // available (tablet users). Because one of the possible cling flows (migration)
689 // is very destructive (wipes out workspaces), we want to prevent this from showing
690 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800691 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800692 }
693 case 17: {
694 // No-op
695 }
696 case 18: {
697 // Due to a data loss bug, some users may have items associated with screen ids
698 // which no longer exist. Since this can cause other problems, and since the user
699 // will never see these items anyway, we use database upgrade as an opportunity to
700 // clean things up.
701 removeOrphanedItems(db);
702 }
703 case 19: {
704 // Add userId column
705 if (!addProfileColumn(db)) {
706 // Old version remains, which means we wipe old data
707 break;
708 }
709 }
710 case 20:
711 if (!updateFolderItemsRank(db, true)) {
712 break;
713 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800714 case 21:
715 // Recreate workspace table with screen id a primary key
716 if (!recreateWorkspaceTable(db)) {
717 break;
718 }
719 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700720 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
721 // Old version remains, which means we wipe old data
722 break;
723 }
724 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700725 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700726 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700727 case 24:
728 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700729 case 25:
730 convertShortcutsToLauncherActivities(db);
731 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 // DB Upgraded successfully
733 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400734 }
735 }
736
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 // DB was not upgraded
738 Log.w(TAG, "Destroying all old data.");
739 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800740 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800741
Adam Cohen9b1d0622014-05-21 19:01:57 -0700742 @Override
743 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
744 // This shouldn't happen -- throw our hands up in the air and start over.
745 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
746 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700747 createEmptyDB(db);
748 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700749
Sunny Goyal42de82f2014-09-26 22:09:29 -0700750 /**
751 * Clears all the data for a fresh start.
752 */
753 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700754 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
755 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
756 onCreate(db);
757 }
758
Sunny Goyald2f38192015-02-25 10:46:34 -0800759 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700760 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
761 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
762 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700763 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700764 db.beginTransaction();
765 Cursor c = null;
766 SQLiteStatement updateStmt = null;
767
768 try {
769 // Only consider the primary user as other users can't have a shortcut.
770 long userSerial = UserManagerCompat.getInstance(mContext)
771 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
772 c = db.query(TABLE_FAVORITES, new String[] {
773 Favorites._ID,
774 Favorites.INTENT,
775 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
776 null, null, null, null);
777
778 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
779 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
780
781 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
782 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
783
784 while (c.moveToNext()) {
785 String intentDescription = c.getString(intentIndex);
786 Intent intent;
787 try {
788 intent = Intent.parseUri(intentDescription, 0);
789 } catch (URISyntaxException e) {
790 Log.e(TAG, "Unable to parse intent", e);
791 continue;
792 }
793
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700794 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700795 continue;
796 }
797
798 long id = c.getLong(idIndex);
799 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700800 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700801 }
802 db.setTransactionSuccessful();
803 } catch (SQLException ex) {
804 Log.w(TAG, "Error deduping shortcuts", ex);
805 } finally {
806 db.endTransaction();
807 if (c != null) {
808 c.close();
809 }
810 if (updateStmt != null) {
811 updateStmt.close();
812 }
813 }
814 }
815
816 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800817 * Recreates workspace table and migrates data to the new table.
818 */
819 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
820 db.beginTransaction();
821 try {
822 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
823 new String[] {LauncherSettings.WorkspaceScreens._ID},
824 null, null, null, null,
825 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
826 ArrayList<Long> sortedIDs = new ArrayList<Long>();
827 long maxId = 0;
828 try {
829 while (c.moveToNext()) {
830 Long id = c.getLong(0);
831 if (!sortedIDs.contains(id)) {
832 sortedIDs.add(id);
833 maxId = Math.max(maxId, id);
834 }
835 }
836 } finally {
837 c.close();
838 }
839
840 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700841 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800842
843 // Add all screen ids back
844 int total = sortedIDs.size();
845 for (int i = 0; i < total; i++) {
846 ContentValues values = new ContentValues();
847 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
848 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
849 addModifiedTime(values);
850 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
851 }
852 db.setTransactionSuccessful();
853 mMaxScreenId = maxId;
854 } catch (SQLException ex) {
855 // Old version remains, which means we wipe old data
856 Log.e(TAG, ex.getMessage(), ex);
857 return false;
858 } finally {
859 db.endTransaction();
860 }
861 return true;
862 }
863
Adam Cohen091440a2015-03-18 14:16:05 -0700864 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800865 db.beginTransaction();
866 try {
867 if (addRankColumn) {
868 // Insert new column for holding rank
869 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
870 }
871
872 // Get a map for folder ID to folder width
873 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
874 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
875 + " GROUP BY container;",
876 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
877
878 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800879 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
880 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800881 new Object[] {c.getLong(1) + 1, c.getLong(0)});
882 }
883
884 c.close();
885 db.setTransactionSuccessful();
886 } catch (SQLException ex) {
887 // Old version remains, which means we wipe old data
888 Log.e(TAG, ex.getMessage(), ex);
889 return false;
890 } finally {
891 db.endTransaction();
892 }
893 return true;
894 }
895
Kenny Guyed131872014-04-30 03:02:21 +0100896 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700897 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
898 // Default to the serial number of this user, for older
899 // shortcuts.
900 long userSerialNumber = userManager.getSerialNumberForUser(
901 UserHandleCompat.myUserHandle());
902 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
903 }
904
905 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100906 db.beginTransaction();
907 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700908 db.execSQL("ALTER TABLE favorites ADD COLUMN "
909 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100910 db.setTransactionSuccessful();
911 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100912 Log.e(TAG, ex.getMessage(), ex);
913 return false;
914 } finally {
915 db.endTransaction();
916 }
917 return true;
918 }
919
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700920 // Generates a new ID to use for an object in your database. This method should be only
921 // called from the main UI thread. As an exception, we do call it when we call the
922 // constructor from the worker thread; however, this doesn't extend until after the
923 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
924 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700925 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700926 public long generateNewItemId() {
927 if (mMaxItemId < 0) {
928 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700929 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700930 mMaxItemId += 1;
931 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700932 }
933
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700934 @Override
935 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
936 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
937 }
938
Chris Wren5dee7af2013-12-20 17:22:11 -0500939 public void checkId(String table, ContentValues values) {
940 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
941 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
942 mMaxScreenId = Math.max(id, mMaxScreenId);
943 } else {
944 mMaxItemId = Math.max(id, mMaxItemId);
945 }
946 }
947
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800949 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700950 }
951
952 // Generates a new ID to use for an workspace screen in your database. This method
953 // should be only called from the main UI thread. As an exception, we do call it when we
954 // call the constructor from the worker thread; however, this doesn't extend until after the
955 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
956 // after that point
957 public long generateNewScreenId() {
958 if (mMaxScreenId < 0) {
959 throw new RuntimeException("Error: max screen id was not initialized");
960 }
961 mMaxScreenId += 1;
962 return mMaxScreenId;
963 }
964
Adam Cohendcd297f2013-06-18 13:13:40 -0700965 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800966 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800967 }
968
Adam Cohen091440a2015-03-18 14:16:05 -0700969 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700970 // 1. Ensure that externally added items have a valid item id
971 long id = generateNewItemId();
972 values.put(LauncherSettings.Favorites._ID, id);
973
974 // 2. In the case of an app widget, and if no app widget id is specified, we
975 // attempt allocate and bind the widget.
976 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
977 if (itemType != null &&
978 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
979 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
980
981 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
982 ComponentName cn = ComponentName.unflattenFromString(
983 values.getAsString(Favorites.APPWIDGET_PROVIDER));
984
985 if (cn != null) {
986 try {
987 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700988 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700989 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700990 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700991 }
992 } catch (RuntimeException e) {
993 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700994 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700995 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700996 } else {
997 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700998 }
999 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001000
1001 // Add screen id if not present
1002 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1003 if (!addScreenIdIfNecessary(screenId)) {
1004 return false;
1005 }
Adam Cohena043fa82014-07-23 14:49:38 -07001006 return true;
1007 }
1008
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001009 // Returns true of screen id exists, or if successfully added
1010 private boolean addScreenIdIfNecessary(long screenId) {
1011 if (!hasScreenId(screenId)) {
1012 int rank = getMaxScreenRank() + 1;
1013
1014 ContentValues v = new ContentValues();
1015 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1016 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1017 if (dbInsertAndCheck(this, getWritableDatabase(),
1018 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1019 return false;
1020 }
1021 }
1022 return true;
1023 }
1024
1025 private boolean hasScreenId(long screenId) {
1026 SQLiteDatabase db = getWritableDatabase();
1027 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1028 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1029 if (c != null) {
1030 int count = c.getCount();
1031 c.close();
1032 return count > 0;
1033 } else {
1034 return false;
1035 }
1036 }
1037
1038 private int getMaxScreenRank() {
1039 SQLiteDatabase db = getWritableDatabase();
1040 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1041 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1042
1043 // get the result
1044 final int maxRankIndex = 0;
1045 int rank = -1;
1046 if (c != null && c.moveToNext()) {
1047 rank = c.getInt(maxRankIndex);
1048 }
1049 if (c != null) {
1050 c.close();
1051 }
1052
1053 return rank;
1054 }
1055
Adam Cohen091440a2015-03-18 14:16:05 -07001056 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001057 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001058 // TODO: Use multiple loaders with fall-back and transaction.
1059 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001060
1061 // Add the screens specified by the items above
1062 Collections.sort(screenIds);
1063 int rank = 0;
1064 ContentValues values = new ContentValues();
1065 for (Long id : screenIds) {
1066 values.clear();
1067 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1068 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1069 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1070 throw new RuntimeException("Failed initialize screen table"
1071 + "from default layout");
1072 }
1073 rank++;
1074 }
1075
1076 // Ensure that the max ids are initialized
1077 mMaxItemId = initializeMaxItemId(db);
1078 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001079
Adam Cohen71483f42014-05-15 14:04:01 -07001080 return count;
1081 }
1082
Adam Cohen091440a2015-03-18 14:16:05 -07001083 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001084 final ContentResolver resolver = mContext.getContentResolver();
1085 Cursor c = null;
1086 int count = 0;
1087 int curScreen = 0;
1088
1089 try {
1090 c = resolver.query(uri, null, null, null, "title ASC");
1091 } catch (Exception e) {
1092 // Ignore
1093 }
1094
Dan Sandlerd5024042014-01-09 15:01:33 -05001095 // We already have a favorites database in the old provider
1096 if (c != null) {
1097 try {
1098 if (c.getCount() > 0) {
1099 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1100 final int intentIndex
1101 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1102 final int titleIndex
1103 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1104 final int iconTypeIndex
1105 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1106 final int iconIndex
1107 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1108 final int iconPackageIndex
1109 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1110 final int iconResourceIndex
1111 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1112 final int containerIndex
1113 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1114 final int itemTypeIndex
1115 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1116 final int screenIndex
1117 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1118 final int cellXIndex
1119 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1120 final int cellYIndex
1121 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1122 final int uriIndex
1123 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1124 final int displayModeIndex
1125 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001126 final int profileIndex
1127 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001128
1129 int i = 0;
1130 int curX = 0;
1131 int curY = 0;
1132
1133 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001134 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1135 final int width = (int) profile.numColumns;
1136 final int height = (int) profile.numRows;
1137 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001138
1139 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1140
Adam Cohen72960972014-01-15 18:13:55 -08001141 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1142 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001143 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001144
1145 while (c.moveToNext()) {
1146 final int itemType = c.getInt(itemTypeIndex);
1147 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1148 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1149 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1150 continue;
1151 }
1152
1153 final int cellX = c.getInt(cellXIndex);
1154 final int cellY = c.getInt(cellYIndex);
1155 final int screen = c.getInt(screenIndex);
1156 int container = c.getInt(containerIndex);
1157 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001158
1159 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1160 UserHandleCompat userHandle;
1161 final long userSerialNumber;
1162 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1163 userSerialNumber = c.getInt(profileIndex);
1164 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1165 } else {
1166 // Default to the serial number of this user, for older
1167 // shortcuts.
1168 userHandle = UserHandleCompat.myUserHandle();
1169 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1170 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001171
1172 if (userHandle == null) {
1173 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1174 continue;
1175 }
1176
Dan Sandlerd5024042014-01-09 15:01:33 -05001177 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001178 + c.getString(titleIndex) + "\" ("
1179 + cellX + "," + cellY + "@"
1180 + LauncherSettings.Favorites.containerToString(container)
1181 + "/" + screen
1182 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001183
1184 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001185
1186 final Intent intent;
1187 final ComponentName cn;
1188 try {
1189 intent = Intent.parseUri(intentStr, 0);
1190 } catch (URISyntaxException e) {
1191 // bogus intent?
1192 Launcher.addDumpLog(TAG,
1193 "skipping invalid intent uri", true);
1194 continue;
1195 }
1196
1197 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001198 if (TextUtils.isEmpty(intentStr)) {
1199 // no intent? no icon
1200 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1201 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001202 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001203 !LauncherModel.isValidPackageActivity(mContext, cn,
1204 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001205 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001206 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001207 "no longer exists.", true);
1208 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001209 } else if (container ==
1210 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1211 // Dedupe icons directly on the workspace
1212
Adam Cohen556f6132014-01-15 15:18:08 -08001213 // Canonicalize
1214 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001215 // does not, so we clear that out to keep them the same.
1216 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001217 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001218 int flags = intent.getFlags();
1219 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001220 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001221 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001222 if (seenIntents.contains(key)) {
1223 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001224 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001225 } else {
1226 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001227 }
1228 }
1229 }
1230
1231 ContentValues values = new ContentValues(c.getColumnCount());
1232 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1233 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1234 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1235 values.put(LauncherSettings.Favorites.ICON_TYPE,
1236 c.getInt(iconTypeIndex));
1237 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1238 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1239 c.getString(iconPackageIndex));
1240 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1241 c.getString(iconResourceIndex));
1242 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1243 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1244 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1245 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1246 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001247 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001248
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001249 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1250 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001251 }
1252
1253 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1254 // In a folder or in the hotseat, preserve position
1255 values.put(LauncherSettings.Favorites.SCREEN, screen);
1256 values.put(LauncherSettings.Favorites.CELLX, cellX);
1257 values.put(LauncherSettings.Favorites.CELLY, cellY);
1258 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001259 // For items contained directly on one of the workspace screen,
1260 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001261 }
1262
1263 values.put(LauncherSettings.Favorites.CONTAINER, container);
1264
Adam Cohen72960972014-01-15 18:13:55 -08001265 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1266 shortcuts.add(values);
1267 } else {
1268 folders.add(values);
1269 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001270 }
1271
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001272 // Now that we have all the hotseat icons, let's go through them left-right
1273 // and assign valid locations for them in the new hotseat
1274 final int N = hotseat.size();
1275 for (int idx=0; idx<N; idx++) {
1276 int hotseatX = hotseat.keyAt(idx);
1277 ContentValues values = hotseat.valueAt(idx);
1278
Adam Cohen2e6da152015-05-06 11:42:25 -07001279 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001280 // let's drop this in the next available hole in the hotseat
1281 while (++hotseatX < hotseatWidth) {
1282 if (hotseat.get(hotseatX) == null) {
1283 // found a spot! move it here
1284 values.put(LauncherSettings.Favorites.SCREEN,
1285 hotseatX);
1286 break;
1287 }
1288 }
1289 }
1290 if (hotseatX >= hotseatWidth) {
1291 // no room for you in the hotseat? it's off to the desktop with you
1292 values.put(LauncherSettings.Favorites.CONTAINER,
1293 Favorites.CONTAINER_DESKTOP);
1294 }
1295 }
1296
Adam Cohen72960972014-01-15 18:13:55 -08001297 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1298 // Folders first
1299 allItems.addAll(folders);
1300 // Then shortcuts
1301 allItems.addAll(shortcuts);
1302
1303 // Layout all the folders
1304 for (ContentValues values: allItems) {
1305 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1306 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1307 // Hotseat items and folder items have already had their
1308 // location information set. Nothing to be done here.
1309 continue;
1310 }
1311 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1312 values.put(LauncherSettings.Favorites.CELLX, curX);
1313 values.put(LauncherSettings.Favorites.CELLY, curY);
1314 curX = (curX + 1) % width;
1315 if (curX == 0) {
1316 curY = (curY + 1);
1317 }
1318 // Leave the last row of icons blank on every screen
1319 if (curY == height - 1) {
1320 curScreen = (int) generateNewScreenId();
1321 curY = 0;
1322 }
1323 }
1324
1325 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001326 db.beginTransaction();
1327 try {
Adam Cohen72960972014-01-15 18:13:55 -08001328 for (ContentValues row: allItems) {
1329 if (row == null) continue;
1330 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001331 < 0) {
1332 return;
1333 } else {
1334 count++;
1335 }
1336 }
1337 db.setTransactionSuccessful();
1338 } finally {
1339 db.endTransaction();
1340 }
1341 }
1342
1343 db.beginTransaction();
1344 try {
1345 for (i=0; i<=curScreen; i++) {
1346 final ContentValues values = new ContentValues();
1347 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1348 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1349 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1350 < 0) {
1351 return;
1352 }
1353 }
1354 db.setTransactionSuccessful();
1355 } finally {
1356 db.endTransaction();
1357 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001358
1359 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001360 }
1361 } finally {
1362 c.close();
1363 }
1364 }
1365
1366 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1367 + (curScreen+1) + " screens", true);
1368
1369 // ensure that new screens are created to hold these icons
1370 setFlagJustLoadedOldDb();
1371
1372 // Update max IDs; very important since we just grabbed IDs from another database
1373 mMaxItemId = initializeMaxItemId(db);
1374 mMaxScreenId = initializeMaxScreenId(db);
1375 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1376 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001377 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001378
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001379 /**
1380 * @return the max _id in the provided table.
1381 */
Adam Cohen091440a2015-03-18 14:16:05 -07001382 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001383 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1384 // get the result
1385 long id = -1;
1386 if (c != null && c.moveToNext()) {
1387 id = c.getLong(0);
1388 }
1389 if (c != null) {
1390 c.close();
1391 }
1392
1393 if (id == -1) {
1394 throw new RuntimeException("Error: could not query max id in " + table);
1395 }
1396
1397 return id;
1398 }
1399
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001400 static class SqlArguments {
1401 public final String table;
1402 public final String where;
1403 public final String[] args;
1404
1405 SqlArguments(Uri url, String where, String[] args) {
1406 if (url.getPathSegments().size() == 1) {
1407 this.table = url.getPathSegments().get(0);
1408 this.where = where;
1409 this.args = args;
1410 } else if (url.getPathSegments().size() != 2) {
1411 throw new IllegalArgumentException("Invalid URI: " + url);
1412 } else if (!TextUtils.isEmpty(where)) {
1413 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1414 } else {
1415 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001416 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001417 this.args = null;
1418 }
1419 }
1420
1421 SqlArguments(Uri url) {
1422 if (url.getPathSegments().size() == 1) {
1423 table = url.getPathSegments().get(0);
1424 where = null;
1425 args = null;
1426 } else {
1427 throw new IllegalArgumentException("Invalid URI: " + url);
1428 }
1429 }
1430 }
Adam Cohen72960972014-01-15 18:13:55 -08001431}