blob: 7674d2acf3f6535cb8f62e257b492883aee256d9 [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 }
273 Bundle result = new Bundle();
274 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
275 return result;
276 }
277 }
278 return null;
279 }
280
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700281 /**
282 * Deletes any empty folder from the DB.
283 * @return Ids of deleted folders.
284 */
285 public List<Long> deleteEmptyFolders() {
286 ArrayList<Long> folderIds = new ArrayList<Long>();
287 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
288 db.beginTransaction();
289 try {
290 // Select folders whose id do not match any container value.
291 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
292 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
293 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
294 LauncherSettings.Favorites.CONTAINER + " FROM "
295 + TABLE_FAVORITES + ")";
296 Cursor c = db.query(TABLE_FAVORITES,
297 new String[] {LauncherSettings.Favorites._ID},
298 selection, null, null, null, null);
299 while (c.moveToNext()) {
300 folderIds.add(c.getLong(0));
301 }
302 c.close();
303 if (folderIds.size() > 0) {
304 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
305 LauncherSettings.Favorites._ID, folderIds), null);
306 }
307 db.setTransactionSuccessful();
308 } catch (SQLException ex) {
309 Log.e(TAG, ex.getMessage(), ex);
310 folderIds.clear();
311 } finally {
312 db.endTransaction();
313 }
314 return folderIds;
315 }
316
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700317 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400318 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400319 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700320 if (mListener != null) {
321 mListener.onLauncherProviderChange();
322 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400323 }
324
Adam Cohen091440a2015-03-18 14:16:05 -0700325 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400326 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 }
328
Adam Cohendcd297f2013-06-18 13:13:40 -0700329 public long generateNewItemId() {
330 return mOpenHelper.generateNewItemId();
331 }
332
333 public long generateNewScreenId() {
334 return mOpenHelper.generateNewScreenId();
335 }
336
Brian Muramatsu5524b492012-10-02 16:55:54 -0700337 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700338 * Clears all the data for a fresh start.
339 */
340 synchronized public void createEmptyDB() {
341 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
342 }
343
Sunny Goyal33d44382014-10-16 09:24:19 -0700344 public void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700345 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700346 }
347
Sunny Goyal42de82f2014-09-26 22:09:29 -0700348 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700349 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700350 * 1) From the app restrictions
351 * 2) From a package provided by play store
352 * 3) From a partner configuration APK, already in the system image
353 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700354 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700355 synchronized public void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700356 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700357
Winson Chungc763c4e2013-07-19 13:49:06 -0700358 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500359 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200360
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700361 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
362 if (loader == null) {
363 loader = AutoInstallsLayout.get(getContext(),
364 mOpenHelper.mAppWidgetHost, mOpenHelper);
365 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700366 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700367 final Partner partner = Partner.get(getContext().getPackageManager());
368 if (partner != null && partner.hasDefaultLayout()) {
369 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700370 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700371 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700372 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700373 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
374 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700375 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700376 }
377 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700378
Sunny Goyal9d219682014-10-23 14:21:02 -0700379 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700380 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700381 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700382 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800383
384 // There might be some partially restored DB items, due to buggy restore logic in
385 // previous versions of launcher.
386 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700387 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700388 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
389 && usingExternallyProvidedLayout) {
390 // Unable to load external layout. Cleanup and load the internal layout.
391 createEmptyDB();
392 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
393 getDefaultLayoutParser());
394 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700395 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700396 }
397 }
398
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700399 /**
400 * Creates workspace loader from an XML resource listed in the app restrictions.
401 *
402 * @return the loader if the restrictions are set and the resource exists; null otherwise.
403 */
404 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
405 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
406 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700407 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700408 return null;
409 }
410
411 Context ctx = getContext();
412 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
413 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700414 if (bundle == null) {
415 return null;
416 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700417
Sunny Goyal35ca8732015-04-06 10:45:31 -0700418 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700419 if (packageName != null) {
420 try {
421 Resources targetResources = ctx.getPackageManager()
422 .getResourcesForApplication(packageName);
423 return AutoInstallsLayout.get(ctx, packageName, targetResources,
424 mOpenHelper.mAppWidgetHost, mOpenHelper);
425 } catch (NameNotFoundException e) {
426 Log.e(TAG, "Target package for restricted profile not found", e);
427 return null;
428 }
429 }
430 return null;
431 }
432
Sunny Goyal9d219682014-10-23 14:21:02 -0700433 private DefaultLayoutParser getDefaultLayoutParser() {
434 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700435 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700436 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
437 mOpenHelper, getContext().getResources(), defaultLayout);
438 }
439
Dan Sandlerd5024042014-01-09 15:01:33 -0500440 public void migrateLauncher2Shortcuts() {
441 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400442 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500443 }
444
Sunny Goyal08f72612015-01-05 13:41:43 -0800445 public void updateFolderItemsRank() {
446 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
447 }
448
Sunny Goyal5c97f512015-05-19 16:03:28 -0700449 public void convertShortcutsToLauncherActivities() {
450 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
451 }
452
453
Dan Sandlerd5024042014-01-09 15:01:33 -0500454 public void deleteDatabase() {
455 // Are you sure? (y/n)
Sunny Goyal33f90e72015-11-30 10:59:35 -0800456 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Dan Sandlerd5024042014-01-09 15:01:33 -0500457 }
458
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700459 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800460 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700461 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700462 private long mMaxItemId = -1;
463 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800464
Winson Chung0b560dd2014-01-21 13:00:26 -0800465 private boolean mNewDbCreated = false;
466
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700467 @Thunk LauncherProviderChangeListener mListener;
468
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100470 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800471 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700472 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700473
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700474 // Table creation sometimes fails silently, which leads to a crash loop.
475 // This way, we will try to create a table every time after crash, so the device
476 // would eventually be able to recover.
477 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
478 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
479 // This operation is a no-op if the table already exists.
480 addFavoritesTable(getWritableDatabase(), true);
481 addWorkspacesTable(getWritableDatabase(), true);
482 }
483
Winson Chung3d503fb2011-07-13 17:25:49 -0700484 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
485 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700486 if (mMaxItemId == -1) {
487 mMaxItemId = initializeMaxItemId(getWritableDatabase());
488 }
489 if (mMaxScreenId == -1) {
490 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700491 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492 }
493
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700494 private boolean tableExists(String tableName) {
495 Cursor c = getReadableDatabase().query(
496 true, "sqlite_master", new String[] {"tbl_name"},
497 "tbl_name = ?", new String[] {tableName},
498 null, null, null, null, null);
499 try {
500 return c.getCount() > 0;
501 } finally {
502 c.close();
503 }
504 }
505
Winson Chung0b560dd2014-01-21 13:00:26 -0800506 public boolean wasNewDbCreated() {
507 return mNewDbCreated;
508 }
509
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800510 @Override
511 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800512 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700513
Adam Cohendcd297f2013-06-18 13:13:40 -0700514 mMaxItemId = 1;
515 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800516 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700517
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700518 addFavoritesTable(db, false);
519 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800520
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700521 // Database was just created, so wipe any previous widgets
522 if (mAppWidgetHost != null) {
523 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700524
525 /**
526 * Send notification that we've deleted the {@link AppWidgetHost},
527 * probably as part of the initial database creation. The receiver may
528 * want to re-call {@link AppWidgetHost#startListening()} to ensure
529 * callbacks are correctly set.
530 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700531 new MainThreadExecutor().execute(new Runnable() {
532
533 @Override
534 public void run() {
535 if (mListener != null) {
536 mListener.onAppWidgetHostReset();
537 }
538 }
539 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700541
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800542 // Fresh and clean launcher DB.
543 mMaxItemId = initializeMaxItemId(db);
544 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700545
546 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700547 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 }
549
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700550 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
551 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
552 long userSerialNumber = userManager.getSerialNumberForUser(
553 UserHandleCompat.myUserHandle());
554 String ifNotExists = optional ? " IF NOT EXISTS " : "";
555
556 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
557 "_id INTEGER PRIMARY KEY," +
558 "title TEXT," +
559 "intent TEXT," +
560 "container INTEGER," +
561 "screen INTEGER," +
562 "cellX INTEGER," +
563 "cellY INTEGER," +
564 "spanX INTEGER," +
565 "spanY INTEGER," +
566 "itemType INTEGER," +
567 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
568 "isShortcut INTEGER," +
569 "iconType INTEGER," +
570 "iconPackage TEXT," +
571 "iconResource TEXT," +
572 "icon BLOB," +
573 "uri TEXT," +
574 "displayMode INTEGER," +
575 "appWidgetProvider TEXT," +
576 "modified INTEGER NOT NULL DEFAULT 0," +
577 "restored INTEGER NOT NULL DEFAULT 0," +
578 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
579 "rank INTEGER NOT NULL DEFAULT 0," +
580 "options INTEGER NOT NULL DEFAULT 0" +
581 ");");
582 }
583
584 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
585 String ifNotExists = optional ? " IF NOT EXISTS " : "";
586 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800587 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400588 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
589 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700590 ");");
591 }
592
Adam Cohen119285e2014-04-02 16:59:08 -0700593 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700594 // Delete items directly on the workspace who's screen id doesn't exist
595 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
596 // AND container = -100"
597 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
598 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700599 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700600 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
601 " AND " +
602 LauncherSettings.Favorites.CONTAINER + " = " +
603 LauncherSettings.Favorites.CONTAINER_DESKTOP;
604 db.execSQL(removeOrphanedDesktopItems);
605
606 // Delete items contained in folders which no longer exist (after above statement)
607 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
608 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
609 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
610 " WHERE " +
611 LauncherSettings.Favorites.CONTAINER + " <> " +
612 LauncherSettings.Favorites.CONTAINER_DESKTOP +
613 " AND "
614 + LauncherSettings.Favorites.CONTAINER + " <> " +
615 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
616 " AND "
617 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
618 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
619 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
620 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
621 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700622 }
623
Winson Chungc763c4e2013-07-19 13:49:06 -0700624 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700625 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700626 }
627
Winson Chungc763c4e2013-07-19 13:49:06 -0700628 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700629 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700630 }
631
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632 @Override
633 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700634 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800635 switch (oldVersion) {
636 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800637 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800638 case 12: {
639 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
640 // to persist workspace screens and their relative order.
641 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700642 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800643 }
644 case 13: {
645 db.beginTransaction();
646 try {
647 // Insert new column for holding widget provider name
648 db.execSQL("ALTER TABLE favorites " +
649 "ADD COLUMN appWidgetProvider TEXT;");
650 db.setTransactionSuccessful();
651 } catch (SQLException ex) {
652 Log.e(TAG, ex.getMessage(), ex);
653 // Old version remains, which means we wipe old data
654 break;
655 } finally {
656 db.endTransaction();
657 }
658 }
659 case 14: {
660 db.beginTransaction();
661 try {
662 // Insert new column for holding update timestamp
663 db.execSQL("ALTER TABLE favorites " +
664 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
665 db.execSQL("ALTER TABLE workspaceScreens " +
666 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
667 db.setTransactionSuccessful();
668 } catch (SQLException ex) {
669 Log.e(TAG, ex.getMessage(), ex);
670 // Old version remains, which means we wipe old data
671 break;
672 } finally {
673 db.endTransaction();
674 }
675 }
676 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700677 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800678 // Old version remains, which means we wipe old data
679 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800680 }
681 }
682 case 16: {
683 // We use the db version upgrade here to identify users who may not have seen
684 // clings yet (because they weren't available), but for whom the clings are now
685 // available (tablet users). Because one of the possible cling flows (migration)
686 // is very destructive (wipes out workspaces), we want to prevent this from showing
687 // until clear data. We do so by marking that the clings have been shown.
Sunny Goyald8043982015-12-17 22:23:02 -0800688 LauncherClings.markFirstRunClingDismissed(mContext);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 }
690 case 17: {
691 // No-op
692 }
693 case 18: {
694 // Due to a data loss bug, some users may have items associated with screen ids
695 // which no longer exist. Since this can cause other problems, and since the user
696 // will never see these items anyway, we use database upgrade as an opportunity to
697 // clean things up.
698 removeOrphanedItems(db);
699 }
700 case 19: {
701 // Add userId column
702 if (!addProfileColumn(db)) {
703 // Old version remains, which means we wipe old data
704 break;
705 }
706 }
707 case 20:
708 if (!updateFolderItemsRank(db, true)) {
709 break;
710 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800711 case 21:
712 // Recreate workspace table with screen id a primary key
713 if (!recreateWorkspaceTable(db)) {
714 break;
715 }
716 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700717 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
718 // Old version remains, which means we wipe old data
719 break;
720 }
721 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700722 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700723 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700724 case 24:
725 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700726 case 25:
727 convertShortcutsToLauncherActivities(db);
728 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800729 // DB Upgraded successfully
730 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400731 }
732 }
733
Sunny Goyala2cc6242015-01-14 14:23:02 -0800734 // DB was not upgraded
735 Log.w(TAG, "Destroying all old data.");
736 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800737 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800738
Adam Cohen9b1d0622014-05-21 19:01:57 -0700739 @Override
740 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
741 // This shouldn't happen -- throw our hands up in the air and start over.
742 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
743 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700744 createEmptyDB(db);
745 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700746
Sunny Goyal42de82f2014-09-26 22:09:29 -0700747 /**
748 * Clears all the data for a fresh start.
749 */
750 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700751 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
752 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
753 onCreate(db);
754 }
755
Sunny Goyald2f38192015-02-25 10:46:34 -0800756 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700757 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
758 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
759 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700760 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700761 db.beginTransaction();
762 Cursor c = null;
763 SQLiteStatement updateStmt = null;
764
765 try {
766 // Only consider the primary user as other users can't have a shortcut.
767 long userSerial = UserManagerCompat.getInstance(mContext)
768 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
769 c = db.query(TABLE_FAVORITES, new String[] {
770 Favorites._ID,
771 Favorites.INTENT,
772 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
773 null, null, null, null);
774
775 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
776 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
777
778 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
779 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
780
781 while (c.moveToNext()) {
782 String intentDescription = c.getString(intentIndex);
783 Intent intent;
784 try {
785 intent = Intent.parseUri(intentDescription, 0);
786 } catch (URISyntaxException e) {
787 Log.e(TAG, "Unable to parse intent", e);
788 continue;
789 }
790
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700791 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700792 continue;
793 }
794
795 long id = c.getLong(idIndex);
796 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700797 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700798 }
799 db.setTransactionSuccessful();
800 } catch (SQLException ex) {
801 Log.w(TAG, "Error deduping shortcuts", ex);
802 } finally {
803 db.endTransaction();
804 if (c != null) {
805 c.close();
806 }
807 if (updateStmt != null) {
808 updateStmt.close();
809 }
810 }
811 }
812
813 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800814 * Recreates workspace table and migrates data to the new table.
815 */
816 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
817 db.beginTransaction();
818 try {
819 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
820 new String[] {LauncherSettings.WorkspaceScreens._ID},
821 null, null, null, null,
822 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
823 ArrayList<Long> sortedIDs = new ArrayList<Long>();
824 long maxId = 0;
825 try {
826 while (c.moveToNext()) {
827 Long id = c.getLong(0);
828 if (!sortedIDs.contains(id)) {
829 sortedIDs.add(id);
830 maxId = Math.max(maxId, id);
831 }
832 }
833 } finally {
834 c.close();
835 }
836
837 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700838 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800839
840 // Add all screen ids back
841 int total = sortedIDs.size();
842 for (int i = 0; i < total; i++) {
843 ContentValues values = new ContentValues();
844 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
845 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
846 addModifiedTime(values);
847 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
848 }
849 db.setTransactionSuccessful();
850 mMaxScreenId = maxId;
851 } catch (SQLException ex) {
852 // Old version remains, which means we wipe old data
853 Log.e(TAG, ex.getMessage(), ex);
854 return false;
855 } finally {
856 db.endTransaction();
857 }
858 return true;
859 }
860
Adam Cohen091440a2015-03-18 14:16:05 -0700861 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800862 db.beginTransaction();
863 try {
864 if (addRankColumn) {
865 // Insert new column for holding rank
866 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
867 }
868
869 // Get a map for folder ID to folder width
870 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
871 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
872 + " GROUP BY container;",
873 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
874
875 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800876 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
877 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800878 new Object[] {c.getLong(1) + 1, c.getLong(0)});
879 }
880
881 c.close();
882 db.setTransactionSuccessful();
883 } catch (SQLException ex) {
884 // Old version remains, which means we wipe old data
885 Log.e(TAG, ex.getMessage(), ex);
886 return false;
887 } finally {
888 db.endTransaction();
889 }
890 return true;
891 }
892
Kenny Guyed131872014-04-30 03:02:21 +0100893 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700894 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
895 // Default to the serial number of this user, for older
896 // shortcuts.
897 long userSerialNumber = userManager.getSerialNumberForUser(
898 UserHandleCompat.myUserHandle());
899 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
900 }
901
902 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100903 db.beginTransaction();
904 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700905 db.execSQL("ALTER TABLE favorites ADD COLUMN "
906 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100907 db.setTransactionSuccessful();
908 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100909 Log.e(TAG, ex.getMessage(), ex);
910 return false;
911 } finally {
912 db.endTransaction();
913 }
914 return true;
915 }
916
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700917 // Generates a new ID to use for an object in your database. This method should be only
918 // called from the main UI thread. As an exception, we do call it when we call the
919 // constructor from the worker thread; however, this doesn't extend until after the
920 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
921 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700922 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700923 public long generateNewItemId() {
924 if (mMaxItemId < 0) {
925 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700926 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700927 mMaxItemId += 1;
928 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700929 }
930
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700931 @Override
932 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
933 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
934 }
935
Chris Wren5dee7af2013-12-20 17:22:11 -0500936 public void checkId(String table, ContentValues values) {
937 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
938 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
939 mMaxScreenId = Math.max(id, mMaxScreenId);
940 } else {
941 mMaxItemId = Math.max(id, mMaxItemId);
942 }
943 }
944
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800946 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 }
948
949 // Generates a new ID to use for an workspace screen in your database. This method
950 // should be only called from the main UI thread. As an exception, we do call it when we
951 // call the constructor from the worker thread; however, this doesn't extend until after the
952 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
953 // after that point
954 public long generateNewScreenId() {
955 if (mMaxScreenId < 0) {
956 throw new RuntimeException("Error: max screen id was not initialized");
957 }
958 mMaxScreenId += 1;
959 return mMaxScreenId;
960 }
961
Adam Cohendcd297f2013-06-18 13:13:40 -0700962 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800963 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800964 }
965
Adam Cohen091440a2015-03-18 14:16:05 -0700966 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700967 // 1. Ensure that externally added items have a valid item id
968 long id = generateNewItemId();
969 values.put(LauncherSettings.Favorites._ID, id);
970
971 // 2. In the case of an app widget, and if no app widget id is specified, we
972 // attempt allocate and bind the widget.
973 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
974 if (itemType != null &&
975 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
976 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
977
978 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
979 ComponentName cn = ComponentName.unflattenFromString(
980 values.getAsString(Favorites.APPWIDGET_PROVIDER));
981
982 if (cn != null) {
983 try {
984 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700985 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700986 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700987 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700988 }
989 } catch (RuntimeException e) {
990 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700991 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700992 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700993 } else {
994 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700995 }
996 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700997
998 // Add screen id if not present
999 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1000 if (!addScreenIdIfNecessary(screenId)) {
1001 return false;
1002 }
Adam Cohena043fa82014-07-23 14:49:38 -07001003 return true;
1004 }
1005
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001006 // Returns true of screen id exists, or if successfully added
1007 private boolean addScreenIdIfNecessary(long screenId) {
1008 if (!hasScreenId(screenId)) {
1009 int rank = getMaxScreenRank() + 1;
1010
1011 ContentValues v = new ContentValues();
1012 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1013 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1014 if (dbInsertAndCheck(this, getWritableDatabase(),
1015 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1016 return false;
1017 }
1018 }
1019 return true;
1020 }
1021
1022 private boolean hasScreenId(long screenId) {
1023 SQLiteDatabase db = getWritableDatabase();
1024 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1025 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1026 if (c != null) {
1027 int count = c.getCount();
1028 c.close();
1029 return count > 0;
1030 } else {
1031 return false;
1032 }
1033 }
1034
1035 private int getMaxScreenRank() {
1036 SQLiteDatabase db = getWritableDatabase();
1037 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1038 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1039
1040 // get the result
1041 final int maxRankIndex = 0;
1042 int rank = -1;
1043 if (c != null && c.moveToNext()) {
1044 rank = c.getInt(maxRankIndex);
1045 }
1046 if (c != null) {
1047 c.close();
1048 }
1049
1050 return rank;
1051 }
1052
Adam Cohen091440a2015-03-18 14:16:05 -07001053 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001054 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001055 // TODO: Use multiple loaders with fall-back and transaction.
1056 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001057
1058 // Add the screens specified by the items above
1059 Collections.sort(screenIds);
1060 int rank = 0;
1061 ContentValues values = new ContentValues();
1062 for (Long id : screenIds) {
1063 values.clear();
1064 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1065 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1066 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1067 throw new RuntimeException("Failed initialize screen table"
1068 + "from default layout");
1069 }
1070 rank++;
1071 }
1072
1073 // Ensure that the max ids are initialized
1074 mMaxItemId = initializeMaxItemId(db);
1075 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001076
Adam Cohen71483f42014-05-15 14:04:01 -07001077 return count;
1078 }
1079
Adam Cohen091440a2015-03-18 14:16:05 -07001080 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001081 final ContentResolver resolver = mContext.getContentResolver();
1082 Cursor c = null;
1083 int count = 0;
1084 int curScreen = 0;
1085
1086 try {
1087 c = resolver.query(uri, null, null, null, "title ASC");
1088 } catch (Exception e) {
1089 // Ignore
1090 }
1091
Dan Sandlerd5024042014-01-09 15:01:33 -05001092 // We already have a favorites database in the old provider
1093 if (c != null) {
1094 try {
1095 if (c.getCount() > 0) {
1096 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1097 final int intentIndex
1098 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1099 final int titleIndex
1100 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1101 final int iconTypeIndex
1102 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1103 final int iconIndex
1104 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1105 final int iconPackageIndex
1106 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1107 final int iconResourceIndex
1108 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1109 final int containerIndex
1110 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1111 final int itemTypeIndex
1112 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1113 final int screenIndex
1114 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1115 final int cellXIndex
1116 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1117 final int cellYIndex
1118 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1119 final int uriIndex
1120 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1121 final int displayModeIndex
1122 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001123 final int profileIndex
1124 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001125
1126 int i = 0;
1127 int curX = 0;
1128 int curY = 0;
1129
1130 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001131 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1132 final int width = (int) profile.numColumns;
1133 final int height = (int) profile.numRows;
1134 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001135
1136 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1137
Adam Cohen72960972014-01-15 18:13:55 -08001138 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1139 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001140 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001141
1142 while (c.moveToNext()) {
1143 final int itemType = c.getInt(itemTypeIndex);
1144 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1145 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1146 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1147 continue;
1148 }
1149
1150 final int cellX = c.getInt(cellXIndex);
1151 final int cellY = c.getInt(cellYIndex);
1152 final int screen = c.getInt(screenIndex);
1153 int container = c.getInt(containerIndex);
1154 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001155
1156 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1157 UserHandleCompat userHandle;
1158 final long userSerialNumber;
1159 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1160 userSerialNumber = c.getInt(profileIndex);
1161 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1162 } else {
1163 // Default to the serial number of this user, for older
1164 // shortcuts.
1165 userHandle = UserHandleCompat.myUserHandle();
1166 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1167 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001168
1169 if (userHandle == null) {
1170 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1171 continue;
1172 }
1173
Dan Sandlerd5024042014-01-09 15:01:33 -05001174 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001175 + c.getString(titleIndex) + "\" ("
1176 + cellX + "," + cellY + "@"
1177 + LauncherSettings.Favorites.containerToString(container)
1178 + "/" + screen
1179 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001180
1181 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001182
1183 final Intent intent;
1184 final ComponentName cn;
1185 try {
1186 intent = Intent.parseUri(intentStr, 0);
1187 } catch (URISyntaxException e) {
1188 // bogus intent?
1189 Launcher.addDumpLog(TAG,
1190 "skipping invalid intent uri", true);
1191 continue;
1192 }
1193
1194 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001195 if (TextUtils.isEmpty(intentStr)) {
1196 // no intent? no icon
1197 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1198 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001199 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001200 !LauncherModel.isValidPackageActivity(mContext, cn,
1201 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001202 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001203 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001204 "no longer exists.", true);
1205 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001206 } else if (container ==
1207 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1208 // Dedupe icons directly on the workspace
1209
Adam Cohen556f6132014-01-15 15:18:08 -08001210 // Canonicalize
1211 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001212 // does not, so we clear that out to keep them the same.
1213 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001214 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001215 int flags = intent.getFlags();
1216 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001217 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001218 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001219 if (seenIntents.contains(key)) {
1220 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001221 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001222 } else {
1223 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001224 }
1225 }
1226 }
1227
1228 ContentValues values = new ContentValues(c.getColumnCount());
1229 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1230 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1231 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1232 values.put(LauncherSettings.Favorites.ICON_TYPE,
1233 c.getInt(iconTypeIndex));
1234 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1235 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1236 c.getString(iconPackageIndex));
1237 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1238 c.getString(iconResourceIndex));
1239 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1240 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1241 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1242 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1243 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001244 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001245
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001246 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1247 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001248 }
1249
1250 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1251 // In a folder or in the hotseat, preserve position
1252 values.put(LauncherSettings.Favorites.SCREEN, screen);
1253 values.put(LauncherSettings.Favorites.CELLX, cellX);
1254 values.put(LauncherSettings.Favorites.CELLY, cellY);
1255 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001256 // For items contained directly on one of the workspace screen,
1257 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001258 }
1259
1260 values.put(LauncherSettings.Favorites.CONTAINER, container);
1261
Adam Cohen72960972014-01-15 18:13:55 -08001262 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1263 shortcuts.add(values);
1264 } else {
1265 folders.add(values);
1266 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001267 }
1268
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001269 // Now that we have all the hotseat icons, let's go through them left-right
1270 // and assign valid locations for them in the new hotseat
1271 final int N = hotseat.size();
1272 for (int idx=0; idx<N; idx++) {
1273 int hotseatX = hotseat.keyAt(idx);
1274 ContentValues values = hotseat.valueAt(idx);
1275
Adam Cohen2e6da152015-05-06 11:42:25 -07001276 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001277 // let's drop this in the next available hole in the hotseat
1278 while (++hotseatX < hotseatWidth) {
1279 if (hotseat.get(hotseatX) == null) {
1280 // found a spot! move it here
1281 values.put(LauncherSettings.Favorites.SCREEN,
1282 hotseatX);
1283 break;
1284 }
1285 }
1286 }
1287 if (hotseatX >= hotseatWidth) {
1288 // no room for you in the hotseat? it's off to the desktop with you
1289 values.put(LauncherSettings.Favorites.CONTAINER,
1290 Favorites.CONTAINER_DESKTOP);
1291 }
1292 }
1293
Adam Cohen72960972014-01-15 18:13:55 -08001294 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1295 // Folders first
1296 allItems.addAll(folders);
1297 // Then shortcuts
1298 allItems.addAll(shortcuts);
1299
1300 // Layout all the folders
1301 for (ContentValues values: allItems) {
1302 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1303 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1304 // Hotseat items and folder items have already had their
1305 // location information set. Nothing to be done here.
1306 continue;
1307 }
1308 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1309 values.put(LauncherSettings.Favorites.CELLX, curX);
1310 values.put(LauncherSettings.Favorites.CELLY, curY);
1311 curX = (curX + 1) % width;
1312 if (curX == 0) {
1313 curY = (curY + 1);
1314 }
1315 // Leave the last row of icons blank on every screen
1316 if (curY == height - 1) {
1317 curScreen = (int) generateNewScreenId();
1318 curY = 0;
1319 }
1320 }
1321
1322 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001323 db.beginTransaction();
1324 try {
Adam Cohen72960972014-01-15 18:13:55 -08001325 for (ContentValues row: allItems) {
1326 if (row == null) continue;
1327 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001328 < 0) {
1329 return;
1330 } else {
1331 count++;
1332 }
1333 }
1334 db.setTransactionSuccessful();
1335 } finally {
1336 db.endTransaction();
1337 }
1338 }
1339
1340 db.beginTransaction();
1341 try {
1342 for (i=0; i<=curScreen; i++) {
1343 final ContentValues values = new ContentValues();
1344 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1345 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1346 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1347 < 0) {
1348 return;
1349 }
1350 }
1351 db.setTransactionSuccessful();
1352 } finally {
1353 db.endTransaction();
1354 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001355
1356 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001357 }
1358 } finally {
1359 c.close();
1360 }
1361 }
1362
1363 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1364 + (curScreen+1) + " screens", true);
1365
1366 // ensure that new screens are created to hold these icons
1367 setFlagJustLoadedOldDb();
1368
1369 // Update max IDs; very important since we just grabbed IDs from another database
1370 mMaxItemId = initializeMaxItemId(db);
1371 mMaxScreenId = initializeMaxScreenId(db);
1372 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1373 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001374 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001375
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001376 /**
1377 * @return the max _id in the provided table.
1378 */
Adam Cohen091440a2015-03-18 14:16:05 -07001379 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001380 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1381 // get the result
1382 long id = -1;
1383 if (c != null && c.moveToNext()) {
1384 id = c.getLong(0);
1385 }
1386 if (c != null) {
1387 c.close();
1388 }
1389
1390 if (id == -1) {
1391 throw new RuntimeException("Error: could not query max id in " + table);
1392 }
1393
1394 return id;
1395 }
1396
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001397 static class SqlArguments {
1398 public final String table;
1399 public final String where;
1400 public final String[] args;
1401
1402 SqlArguments(Uri url, String where, String[] args) {
1403 if (url.getPathSegments().size() == 1) {
1404 this.table = url.getPathSegments().get(0);
1405 this.where = where;
1406 this.args = args;
1407 } else if (url.getPathSegments().size() != 2) {
1408 throw new IllegalArgumentException("Invalid URI: " + url);
1409 } else if (!TextUtils.isEmpty(where)) {
1410 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1411 } else {
1412 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001413 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001414 this.args = null;
1415 }
1416 }
1417
1418 SqlArguments(Uri url) {
1419 if (url.getPathSegments().size() == 1) {
1420 table = url.getPathSegments().get(0);
1421 where = null;
1422 args = null;
1423 } else {
1424 throw new IllegalArgumentException("Invalid URI: " + url);
1425 }
1426 }
1427 }
Adam Cohen72960972014-01-15 18:13:55 -08001428}