blob: 3044b98cfa854f430b3568368146b69e7f0885ab [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080046import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050050import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070068 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080069 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Sunny Goyal5c97f512015-05-19 16:03:28 -070071 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072
Sunny Goyale5bb7052015-07-27 14:36:07 -070073 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070074
Sunny Goyal18b640c2015-04-17 09:24:01 -070075 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
76 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080077 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070079 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
80
Sunny Goyal383c5072015-06-12 21:18:53 -070081 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070082 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080087 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080089 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 return true;
92 }
93
Winson Chung0b560dd2014-01-21 13:00:26 -080094 public boolean wasNewDbCreated() {
95 return mOpenHelper.wasNewDbCreated();
96 }
97
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
99 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700100 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public String getType(Uri uri) {
105 SqlArguments args = new SqlArguments(uri, null, null);
106 if (TextUtils.isEmpty(args.where)) {
107 return "vnd.android.cursor.dir/" + args.table;
108 } else {
109 return "vnd.android.cursor.item/" + args.table;
110 }
111 }
112
113 @Override
114 public Cursor query(Uri uri, String[] projection, String selection,
115 String[] selectionArgs, String sortOrder) {
116
117 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
118 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
119 qb.setTables(args.table);
120
Romain Guy73b979d2009-06-09 12:57:21 -0700121 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
123 result.setNotificationUri(getContext().getContentResolver(), uri);
124
125 return result;
126 }
127
Adam Cohen091440a2015-03-18 14:16:05 -0700128 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500130 if (values == null) {
131 throw new RuntimeException("Error: attempting to insert null values");
132 }
Adam Cohen71483f42014-05-15 14:04:01 -0700133 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 throw new RuntimeException("Error: attempting to add item without specifying an id");
135 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500136 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 return db.insert(table, nullColumnHack, values);
138 }
139
Sunny Goyald1064182015-08-13 12:08:30 -0700140 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700141 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700142 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
143 if (app != null) {
144 app.reloadWorkspace();
145 }
146 }
147 }
148
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149 @Override
150 public Uri insert(Uri uri, ContentValues initialValues) {
151 SqlArguments args = new SqlArguments(uri);
152
Sunny Goyald1064182015-08-13 12:08:30 -0700153 // In very limited cases, we support system|signature permission apps to modify the db.
154 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700155 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
156 return null;
157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400161 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800163 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700166 notifyListeners();
167
Sunny Goyalc74e4192015-09-08 14:01:03 -0700168 if (Utilities.ATLEAST_MARSHMALLOW) {
169 reloadLauncherIfExternal();
170 } else {
171 // Deprecated behavior to support legacy devices which rely on provider callbacks.
172 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
173 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
174 app.reloadWorkspace();
175 }
176
177 String notify = uri.getQueryParameter("notify");
178 if (notify == null || "true".equals(notify)) {
179 getContext().getContentResolver().notifyChange(uri, null);
180 }
181 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 return uri;
183 }
184
Adam Cohena043fa82014-07-23 14:49:38 -0700185
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186 @Override
187 public int bulkInsert(Uri uri, ContentValues[] values) {
188 SqlArguments args = new SqlArguments(uri);
189
190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
191 db.beginTransaction();
192 try {
193 int numValues = values.length;
194 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700196 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
197 return 0;
198 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199 }
200 db.setTransactionSuccessful();
201 } finally {
202 db.endTransaction();
203 }
204
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700205 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700206 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800207 return values.length;
208 }
209
210 @Override
Yura085c8532014-02-11 15:15:29 +0000211 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
212 throws OperationApplicationException {
213 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
214 db.beginTransaction();
215 try {
216 ContentProviderResult[] result = super.applyBatch(operations);
217 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700218 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000219 return result;
220 } finally {
221 db.endTransaction();
222 }
223 }
224
225 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800226 public int delete(Uri uri, String selection, String[] selectionArgs) {
227 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
228
229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
230 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700231 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232
Sunny Goyald1064182015-08-13 12:08:30 -0700233 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 return count;
235 }
236
237 @Override
238 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
239 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
240
Chris Wren1ada10d2013-09-13 18:01:38 -0400241 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
243 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700244 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800245
Sunny Goyald1064182015-08-13 12:08:30 -0700246 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800247 return count;
248 }
249
Sunny Goyal7779d622015-06-11 16:18:39 -0700250 @Override
251 public Bundle call(String method, String arg, Bundle extras) {
252 if (Binder.getCallingUid() != Process.myUid()) {
253 return null;
254 }
255
256 switch (method) {
257 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
258 Bundle result = new Bundle();
259 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
260 getContext().getSharedPreferences(
261 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
262 .getBoolean(arg, extras.getBoolean(
263 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
264 return result;
265 }
266 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
267 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
268 getContext().getSharedPreferences(
269 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
270 .edit().putBoolean(arg, value).apply();
271 if (mListener != null) {
272 mListener.onSettingsChanged(arg, value);
273 }
274 Bundle result = new Bundle();
275 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
276 return result;
277 }
278 }
279 return null;
280 }
281
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700282 /**
283 * Deletes any empty folder from the DB.
284 * @return Ids of deleted folders.
285 */
286 public List<Long> deleteEmptyFolders() {
287 ArrayList<Long> folderIds = new ArrayList<Long>();
288 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
289 db.beginTransaction();
290 try {
291 // Select folders whose id do not match any container value.
292 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
293 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
294 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
295 LauncherSettings.Favorites.CONTAINER + " FROM "
296 + TABLE_FAVORITES + ")";
297 Cursor c = db.query(TABLE_FAVORITES,
298 new String[] {LauncherSettings.Favorites._ID},
299 selection, null, null, null, null);
300 while (c.moveToNext()) {
301 folderIds.add(c.getLong(0));
302 }
303 c.close();
304 if (folderIds.size() > 0) {
305 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
306 LauncherSettings.Favorites._ID, folderIds), null);
307 }
308 db.setTransactionSuccessful();
309 } catch (SQLException ex) {
310 Log.e(TAG, ex.getMessage(), ex);
311 folderIds.clear();
312 } finally {
313 db.endTransaction();
314 }
315 return folderIds;
316 }
317
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700318 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400319 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400320 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700321 if (mListener != null) {
322 mListener.onLauncherProviderChange();
323 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400324 }
325
Adam Cohen091440a2015-03-18 14:16:05 -0700326 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400327 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 }
329
Adam Cohendcd297f2013-06-18 13:13:40 -0700330 public long generateNewItemId() {
331 return mOpenHelper.generateNewItemId();
332 }
333
Winson Chungc763c4e2013-07-19 13:49:06 -0700334 public void updateMaxItemId(long id) {
335 mOpenHelper.updateMaxItemId(id);
336 }
337
Adam Cohendcd297f2013-06-18 13:13:40 -0700338 public long generateNewScreenId() {
339 return mOpenHelper.generateNewScreenId();
340 }
341
Brian Muramatsu5524b492012-10-02 16:55:54 -0700342 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700343 * Clears all the data for a fresh start.
344 */
345 synchronized public void createEmptyDB() {
346 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
347 }
348
Sunny Goyal33d44382014-10-16 09:24:19 -0700349 public void clearFlagEmptyDbCreated() {
350 String spKey = LauncherAppState.getSharedPreferencesKey();
351 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
352 .edit()
353 .remove(EMPTY_DATABASE_CREATED)
354 .commit();
355 }
356
Sunny Goyal42de82f2014-09-26 22:09:29 -0700357 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700358 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700359 * 1) From the app restrictions
360 * 2) From a package provided by play store
361 * 3) From a partner configuration APK, already in the system image
362 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700363 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700364 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400365 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700366 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700367
Winson Chungc763c4e2013-07-19 13:49:06 -0700368 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500369 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200370
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700371 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
372 if (loader == null) {
373 loader = AutoInstallsLayout.get(getContext(),
374 mOpenHelper.mAppWidgetHost, mOpenHelper);
375 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700376 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700377 final Partner partner = Partner.get(getContext().getPackageManager());
378 if (partner != null && partner.hasDefaultLayout()) {
379 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700380 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700381 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700382 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700383 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
384 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700385 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700386 }
387 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700388
Sunny Goyal9d219682014-10-23 14:21:02 -0700389 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700390 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700391 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700392 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800393
394 // There might be some partially restored DB items, due to buggy restore logic in
395 // previous versions of launcher.
396 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700397 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700398 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
399 && usingExternallyProvidedLayout) {
400 // Unable to load external layout. Cleanup and load the internal layout.
401 createEmptyDB();
402 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
403 getDefaultLayoutParser());
404 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700405 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700406 }
407 }
408
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700409 /**
410 * Creates workspace loader from an XML resource listed in the app restrictions.
411 *
412 * @return the loader if the restrictions are set and the resource exists; null otherwise.
413 */
414 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
415 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
416 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700417 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700418 return null;
419 }
420
421 Context ctx = getContext();
422 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
423 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700424 if (bundle == null) {
425 return null;
426 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700427
Sunny Goyal35ca8732015-04-06 10:45:31 -0700428 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700429 if (packageName != null) {
430 try {
431 Resources targetResources = ctx.getPackageManager()
432 .getResourcesForApplication(packageName);
433 return AutoInstallsLayout.get(ctx, packageName, targetResources,
434 mOpenHelper.mAppWidgetHost, mOpenHelper);
435 } catch (NameNotFoundException e) {
436 Log.e(TAG, "Target package for restricted profile not found", e);
437 return null;
438 }
439 }
440 return null;
441 }
442
Sunny Goyal9d219682014-10-23 14:21:02 -0700443 private DefaultLayoutParser getDefaultLayoutParser() {
444 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700445 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700446 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
447 mOpenHelper, getContext().getResources(), defaultLayout);
448 }
449
Dan Sandlerd5024042014-01-09 15:01:33 -0500450 public void migrateLauncher2Shortcuts() {
451 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400452 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500453 }
454
Sunny Goyal08f72612015-01-05 13:41:43 -0800455 public void updateFolderItemsRank() {
456 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
457 }
458
Sunny Goyal5c97f512015-05-19 16:03:28 -0700459 public void convertShortcutsToLauncherActivities() {
460 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
461 }
462
463
Dan Sandlerd5024042014-01-09 15:01:33 -0500464 public void deleteDatabase() {
465 // Are you sure? (y/n)
466 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500467 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500468 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500469 if (dbFile.exists()) {
470 SQLiteDatabase.deleteDatabase(dbFile);
471 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500472 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700473 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500474 }
475
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700476 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700478 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700479 private long mMaxItemId = -1;
480 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800481
Winson Chung0b560dd2014-01-21 13:00:26 -0800482 private boolean mNewDbCreated = false;
483
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700484 @Thunk LauncherProviderChangeListener mListener;
485
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800486 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100487 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800488 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700489 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700490
491 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
492 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700493 if (mMaxItemId == -1) {
494 mMaxItemId = initializeMaxItemId(getWritableDatabase());
495 }
496 if (mMaxScreenId == -1) {
497 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700498 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800499 }
500
Winson Chung0b560dd2014-01-21 13:00:26 -0800501 public boolean wasNewDbCreated() {
502 return mNewDbCreated;
503 }
504
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800505 @Override
506 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800507 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700508
Adam Cohendcd297f2013-06-18 13:13:40 -0700509 mMaxItemId = 1;
510 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800511 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700512
Kenny Guyed131872014-04-30 03:02:21 +0100513 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
514 long userSerialNumber = userManager.getSerialNumberForUser(
515 UserHandleCompat.myUserHandle());
516
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800517 db.execSQL("CREATE TABLE favorites (" +
518 "_id INTEGER PRIMARY KEY," +
519 "title TEXT," +
520 "intent TEXT," +
521 "container INTEGER," +
522 "screen INTEGER," +
523 "cellX INTEGER," +
524 "cellY INTEGER," +
525 "spanX INTEGER," +
526 "spanY INTEGER," +
527 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700528 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800529 "isShortcut INTEGER," +
530 "iconType INTEGER," +
531 "iconPackage TEXT," +
532 "iconResource TEXT," +
533 "icon BLOB," +
534 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400535 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400536 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500537 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100538 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800539 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700540 "rank INTEGER NOT NULL DEFAULT 0," +
541 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700543 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800544
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700545 // Database was just created, so wipe any previous widgets
546 if (mAppWidgetHost != null) {
547 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700548
549 /**
550 * Send notification that we've deleted the {@link AppWidgetHost},
551 * probably as part of the initial database creation. The receiver may
552 * want to re-call {@link AppWidgetHost#startListening()} to ensure
553 * callbacks are correctly set.
554 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700555 new MainThreadExecutor().execute(new Runnable() {
556
557 @Override
558 public void run() {
559 if (mListener != null) {
560 mListener.onAppWidgetHostReset();
561 }
562 }
563 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800564 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700565
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800566 // Fresh and clean launcher DB.
567 mMaxItemId = initializeMaxItemId(db);
568 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700569
570 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700571 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 }
573
Adam Cohendcd297f2013-06-18 13:13:40 -0700574 private void addWorkspacesTable(SQLiteDatabase db) {
575 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800576 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400577 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
578 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 ");");
580 }
581
Adam Cohen119285e2014-04-02 16:59:08 -0700582 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700583 // Delete items directly on the workspace who's screen id doesn't exist
584 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
585 // AND container = -100"
586 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
587 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700588 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700589 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
590 " AND " +
591 LauncherSettings.Favorites.CONTAINER + " = " +
592 LauncherSettings.Favorites.CONTAINER_DESKTOP;
593 db.execSQL(removeOrphanedDesktopItems);
594
595 // Delete items contained in folders which no longer exist (after above statement)
596 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
597 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
598 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
599 " WHERE " +
600 LauncherSettings.Favorites.CONTAINER + " <> " +
601 LauncherSettings.Favorites.CONTAINER_DESKTOP +
602 " AND "
603 + LauncherSettings.Favorites.CONTAINER + " <> " +
604 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
605 " AND "
606 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
607 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
608 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
609 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
610 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700611 }
612
Winson Chungc763c4e2013-07-19 13:49:06 -0700613 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400614 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700615 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800616 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700617 }
618
Winson Chungc763c4e2013-07-19 13:49:06 -0700619 private void setFlagEmptyDbCreated() {
620 String spKey = LauncherAppState.getSharedPreferencesKey();
621 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800622 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700623 }
624
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625 @Override
626 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700627 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800628 switch (oldVersion) {
629 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800630 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800631 case 12: {
632 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
633 // to persist workspace screens and their relative order.
634 mMaxScreenId = 0;
635 addWorkspacesTable(db);
636 }
637 case 13: {
638 db.beginTransaction();
639 try {
640 // Insert new column for holding widget provider name
641 db.execSQL("ALTER TABLE favorites " +
642 "ADD COLUMN appWidgetProvider TEXT;");
643 db.setTransactionSuccessful();
644 } catch (SQLException ex) {
645 Log.e(TAG, ex.getMessage(), ex);
646 // Old version remains, which means we wipe old data
647 break;
648 } finally {
649 db.endTransaction();
650 }
651 }
652 case 14: {
653 db.beginTransaction();
654 try {
655 // Insert new column for holding update timestamp
656 db.execSQL("ALTER TABLE favorites " +
657 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
658 db.execSQL("ALTER TABLE workspaceScreens " +
659 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
660 db.setTransactionSuccessful();
661 } catch (SQLException ex) {
662 Log.e(TAG, ex.getMessage(), ex);
663 // Old version remains, which means we wipe old data
664 break;
665 } finally {
666 db.endTransaction();
667 }
668 }
669 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700670 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 // Old version remains, which means we wipe old data
672 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800673 }
674 }
675 case 16: {
676 // We use the db version upgrade here to identify users who may not have seen
677 // clings yet (because they weren't available), but for whom the clings are now
678 // available (tablet users). Because one of the possible cling flows (migration)
679 // is very destructive (wipes out workspaces), we want to prevent this from showing
680 // until clear data. We do so by marking that the clings have been shown.
681 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
682 }
683 case 17: {
684 // No-op
685 }
686 case 18: {
687 // Due to a data loss bug, some users may have items associated with screen ids
688 // which no longer exist. Since this can cause other problems, and since the user
689 // will never see these items anyway, we use database upgrade as an opportunity to
690 // clean things up.
691 removeOrphanedItems(db);
692 }
693 case 19: {
694 // Add userId column
695 if (!addProfileColumn(db)) {
696 // Old version remains, which means we wipe old data
697 break;
698 }
699 }
700 case 20:
701 if (!updateFolderItemsRank(db, true)) {
702 break;
703 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800704 case 21:
705 // Recreate workspace table with screen id a primary key
706 if (!recreateWorkspaceTable(db)) {
707 break;
708 }
709 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700710 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
711 // Old version remains, which means we wipe old data
712 break;
713 }
714 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700715 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700716 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700717 case 24:
718 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700719 case 25:
720 convertShortcutsToLauncherActivities(db);
721 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800722 // DB Upgraded successfully
723 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400724 }
725 }
726
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 // DB was not upgraded
728 Log.w(TAG, "Destroying all old data.");
729 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800730 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800731
Adam Cohen9b1d0622014-05-21 19:01:57 -0700732 @Override
733 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
734 // This shouldn't happen -- throw our hands up in the air and start over.
735 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
736 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700737 createEmptyDB(db);
738 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700739
Sunny Goyal42de82f2014-09-26 22:09:29 -0700740 /**
741 * Clears all the data for a fresh start.
742 */
743 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700744 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
745 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
746 onCreate(db);
747 }
748
Sunny Goyald2f38192015-02-25 10:46:34 -0800749 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700750 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
751 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
752 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700753 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700754 db.beginTransaction();
755 Cursor c = null;
756 SQLiteStatement updateStmt = null;
757
758 try {
759 // Only consider the primary user as other users can't have a shortcut.
760 long userSerial = UserManagerCompat.getInstance(mContext)
761 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
762 c = db.query(TABLE_FAVORITES, new String[] {
763 Favorites._ID,
764 Favorites.INTENT,
765 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
766 null, null, null, null);
767
768 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
769 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
770
771 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
772 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
773
774 while (c.moveToNext()) {
775 String intentDescription = c.getString(intentIndex);
776 Intent intent;
777 try {
778 intent = Intent.parseUri(intentDescription, 0);
779 } catch (URISyntaxException e) {
780 Log.e(TAG, "Unable to parse intent", e);
781 continue;
782 }
783
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700784 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700785 continue;
786 }
787
788 long id = c.getLong(idIndex);
789 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700790 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700791 }
792 db.setTransactionSuccessful();
793 } catch (SQLException ex) {
794 Log.w(TAG, "Error deduping shortcuts", ex);
795 } finally {
796 db.endTransaction();
797 if (c != null) {
798 c.close();
799 }
800 if (updateStmt != null) {
801 updateStmt.close();
802 }
803 }
804 }
805
806 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800807 * Recreates workspace table and migrates data to the new table.
808 */
809 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
810 db.beginTransaction();
811 try {
812 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
813 new String[] {LauncherSettings.WorkspaceScreens._ID},
814 null, null, null, null,
815 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
816 ArrayList<Long> sortedIDs = new ArrayList<Long>();
817 long maxId = 0;
818 try {
819 while (c.moveToNext()) {
820 Long id = c.getLong(0);
821 if (!sortedIDs.contains(id)) {
822 sortedIDs.add(id);
823 maxId = Math.max(maxId, id);
824 }
825 }
826 } finally {
827 c.close();
828 }
829
830 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
831 addWorkspacesTable(db);
832
833 // Add all screen ids back
834 int total = sortedIDs.size();
835 for (int i = 0; i < total; i++) {
836 ContentValues values = new ContentValues();
837 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
838 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
839 addModifiedTime(values);
840 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
841 }
842 db.setTransactionSuccessful();
843 mMaxScreenId = maxId;
844 } catch (SQLException ex) {
845 // Old version remains, which means we wipe old data
846 Log.e(TAG, ex.getMessage(), ex);
847 return false;
848 } finally {
849 db.endTransaction();
850 }
851 return true;
852 }
853
Adam Cohen091440a2015-03-18 14:16:05 -0700854 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800855 db.beginTransaction();
856 try {
857 if (addRankColumn) {
858 // Insert new column for holding rank
859 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
860 }
861
862 // Get a map for folder ID to folder width
863 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
864 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
865 + " GROUP BY container;",
866 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
867
868 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800869 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
870 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800871 new Object[] {c.getLong(1) + 1, c.getLong(0)});
872 }
873
874 c.close();
875 db.setTransactionSuccessful();
876 } catch (SQLException ex) {
877 // Old version remains, which means we wipe old data
878 Log.e(TAG, ex.getMessage(), ex);
879 return false;
880 } finally {
881 db.endTransaction();
882 }
883 return true;
884 }
885
Kenny Guyed131872014-04-30 03:02:21 +0100886 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700887 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
888 // Default to the serial number of this user, for older
889 // shortcuts.
890 long userSerialNumber = userManager.getSerialNumberForUser(
891 UserHandleCompat.myUserHandle());
892 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
893 }
894
895 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100896 db.beginTransaction();
897 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700898 db.execSQL("ALTER TABLE favorites ADD COLUMN "
899 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100900 db.setTransactionSuccessful();
901 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100902 Log.e(TAG, ex.getMessage(), ex);
903 return false;
904 } finally {
905 db.endTransaction();
906 }
907 return true;
908 }
909
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700910 // Generates a new ID to use for an object in your database. This method should be only
911 // called from the main UI thread. As an exception, we do call it when we call the
912 // constructor from the worker thread; however, this doesn't extend until after the
913 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
914 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700915 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700916 public long generateNewItemId() {
917 if (mMaxItemId < 0) {
918 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700919 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700920 mMaxItemId += 1;
921 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700922 }
923
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700924 @Override
925 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
926 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
927 }
928
Winson Chungc763c4e2013-07-19 13:49:06 -0700929 public void updateMaxItemId(long id) {
930 mMaxItemId = id + 1;
931 }
932
Chris Wren5dee7af2013-12-20 17:22:11 -0500933 public void checkId(String table, ContentValues values) {
934 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
935 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
936 mMaxScreenId = Math.max(id, mMaxScreenId);
937 } else {
938 mMaxItemId = Math.max(id, mMaxItemId);
939 }
940 }
941
Adam Cohendcd297f2013-06-18 13:13:40 -0700942 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800943 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700944 }
945
946 // Generates a new ID to use for an workspace screen in your database. This method
947 // should be only called from the main UI thread. As an exception, we do call it when we
948 // call the constructor from the worker thread; however, this doesn't extend until after the
949 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
950 // after that point
951 public long generateNewScreenId() {
952 if (mMaxScreenId < 0) {
953 throw new RuntimeException("Error: max screen id was not initialized");
954 }
955 mMaxScreenId += 1;
956 return mMaxScreenId;
957 }
958
Adam Cohendcd297f2013-06-18 13:13:40 -0700959 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800960 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800961 }
962
Adam Cohen091440a2015-03-18 14:16:05 -0700963 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700964 // 1. Ensure that externally added items have a valid item id
965 long id = generateNewItemId();
966 values.put(LauncherSettings.Favorites._ID, id);
967
968 // 2. In the case of an app widget, and if no app widget id is specified, we
969 // attempt allocate and bind the widget.
970 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
971 if (itemType != null &&
972 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
973 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
974
975 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
976 ComponentName cn = ComponentName.unflattenFromString(
977 values.getAsString(Favorites.APPWIDGET_PROVIDER));
978
979 if (cn != null) {
980 try {
981 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700982 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700983 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700984 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700985 }
986 } catch (RuntimeException e) {
987 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700988 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700989 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700990 } else {
991 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700992 }
993 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700994
995 // Add screen id if not present
996 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
997 if (!addScreenIdIfNecessary(screenId)) {
998 return false;
999 }
Adam Cohena043fa82014-07-23 14:49:38 -07001000 return true;
1001 }
1002
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001003 // Returns true of screen id exists, or if successfully added
1004 private boolean addScreenIdIfNecessary(long screenId) {
1005 if (!hasScreenId(screenId)) {
1006 int rank = getMaxScreenRank() + 1;
1007
1008 ContentValues v = new ContentValues();
1009 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1010 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1011 if (dbInsertAndCheck(this, getWritableDatabase(),
1012 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1013 return false;
1014 }
1015 }
1016 return true;
1017 }
1018
1019 private boolean hasScreenId(long screenId) {
1020 SQLiteDatabase db = getWritableDatabase();
1021 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1022 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1023 if (c != null) {
1024 int count = c.getCount();
1025 c.close();
1026 return count > 0;
1027 } else {
1028 return false;
1029 }
1030 }
1031
1032 private int getMaxScreenRank() {
1033 SQLiteDatabase db = getWritableDatabase();
1034 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1035 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1036
1037 // get the result
1038 final int maxRankIndex = 0;
1039 int rank = -1;
1040 if (c != null && c.moveToNext()) {
1041 rank = c.getInt(maxRankIndex);
1042 }
1043 if (c != null) {
1044 c.close();
1045 }
1046
1047 return rank;
1048 }
1049
Adam Cohen091440a2015-03-18 14:16:05 -07001050 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001051 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001052 // TODO: Use multiple loaders with fall-back and transaction.
1053 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001054
1055 // Add the screens specified by the items above
1056 Collections.sort(screenIds);
1057 int rank = 0;
1058 ContentValues values = new ContentValues();
1059 for (Long id : screenIds) {
1060 values.clear();
1061 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1062 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1063 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1064 throw new RuntimeException("Failed initialize screen table"
1065 + "from default layout");
1066 }
1067 rank++;
1068 }
1069
1070 // Ensure that the max ids are initialized
1071 mMaxItemId = initializeMaxItemId(db);
1072 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001073
Adam Cohen71483f42014-05-15 14:04:01 -07001074 return count;
1075 }
1076
Adam Cohen091440a2015-03-18 14:16:05 -07001077 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001078 final ContentResolver resolver = mContext.getContentResolver();
1079 Cursor c = null;
1080 int count = 0;
1081 int curScreen = 0;
1082
1083 try {
1084 c = resolver.query(uri, null, null, null, "title ASC");
1085 } catch (Exception e) {
1086 // Ignore
1087 }
1088
Dan Sandlerd5024042014-01-09 15:01:33 -05001089 // We already have a favorites database in the old provider
1090 if (c != null) {
1091 try {
1092 if (c.getCount() > 0) {
1093 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1094 final int intentIndex
1095 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1096 final int titleIndex
1097 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1098 final int iconTypeIndex
1099 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1100 final int iconIndex
1101 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1102 final int iconPackageIndex
1103 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1104 final int iconResourceIndex
1105 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1106 final int containerIndex
1107 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1108 final int itemTypeIndex
1109 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1110 final int screenIndex
1111 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1112 final int cellXIndex
1113 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1114 final int cellYIndex
1115 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001116 final int profileIndex
1117 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001118
1119 int i = 0;
1120 int curX = 0;
1121 int curY = 0;
1122
1123 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001124 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1125 final int width = (int) profile.numColumns;
1126 final int height = (int) profile.numRows;
1127 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001128
1129 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1130
Adam Cohen72960972014-01-15 18:13:55 -08001131 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1132 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001133 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001134
1135 while (c.moveToNext()) {
1136 final int itemType = c.getInt(itemTypeIndex);
1137 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1138 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1139 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1140 continue;
1141 }
1142
1143 final int cellX = c.getInt(cellXIndex);
1144 final int cellY = c.getInt(cellYIndex);
1145 final int screen = c.getInt(screenIndex);
1146 int container = c.getInt(containerIndex);
1147 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001148
1149 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1150 UserHandleCompat userHandle;
1151 final long userSerialNumber;
1152 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1153 userSerialNumber = c.getInt(profileIndex);
1154 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1155 } else {
1156 // Default to the serial number of this user, for older
1157 // shortcuts.
1158 userHandle = UserHandleCompat.myUserHandle();
1159 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1160 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001161
1162 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001163 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001164 continue;
1165 }
1166
Dan Sandlerd5024042014-01-09 15:01:33 -05001167 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001168
1169 final Intent intent;
1170 final ComponentName cn;
1171 try {
1172 intent = Intent.parseUri(intentStr, 0);
1173 } catch (URISyntaxException e) {
1174 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001175 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001176 continue;
1177 }
1178
1179 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001180 if (TextUtils.isEmpty(intentStr)) {
1181 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001182 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001183 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001184 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001185 !LauncherModel.isValidPackageActivity(mContext, cn,
1186 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001187 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001188 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001189 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001190 } else if (container ==
1191 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1192 // Dedupe icons directly on the workspace
1193
Adam Cohen556f6132014-01-15 15:18:08 -08001194 // Canonicalize
1195 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001196 // does not, so we clear that out to keep them the same.
1197 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001198 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001199 int flags = intent.getFlags();
1200 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001201 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001202 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001203 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001204 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001205 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001206 } else {
1207 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001208 }
1209 }
1210 }
1211
1212 ContentValues values = new ContentValues(c.getColumnCount());
1213 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1214 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1215 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1216 values.put(LauncherSettings.Favorites.ICON_TYPE,
1217 c.getInt(iconTypeIndex));
1218 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1219 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1220 c.getString(iconPackageIndex));
1221 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1222 c.getString(iconResourceIndex));
1223 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1224 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001225 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001226
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001227 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1228 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001229 }
1230
1231 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1232 // In a folder or in the hotseat, preserve position
1233 values.put(LauncherSettings.Favorites.SCREEN, screen);
1234 values.put(LauncherSettings.Favorites.CELLX, cellX);
1235 values.put(LauncherSettings.Favorites.CELLY, cellY);
1236 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001237 // For items contained directly on one of the workspace screen,
1238 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001239 }
1240
1241 values.put(LauncherSettings.Favorites.CONTAINER, container);
1242
Adam Cohen72960972014-01-15 18:13:55 -08001243 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1244 shortcuts.add(values);
1245 } else {
1246 folders.add(values);
1247 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001248 }
1249
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001250 // Now that we have all the hotseat icons, let's go through them left-right
1251 // and assign valid locations for them in the new hotseat
1252 final int N = hotseat.size();
1253 for (int idx=0; idx<N; idx++) {
1254 int hotseatX = hotseat.keyAt(idx);
1255 ContentValues values = hotseat.valueAt(idx);
1256
Adam Cohen2e6da152015-05-06 11:42:25 -07001257 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001258 // let's drop this in the next available hole in the hotseat
1259 while (++hotseatX < hotseatWidth) {
1260 if (hotseat.get(hotseatX) == null) {
1261 // found a spot! move it here
1262 values.put(LauncherSettings.Favorites.SCREEN,
1263 hotseatX);
1264 break;
1265 }
1266 }
1267 }
1268 if (hotseatX >= hotseatWidth) {
1269 // no room for you in the hotseat? it's off to the desktop with you
1270 values.put(LauncherSettings.Favorites.CONTAINER,
1271 Favorites.CONTAINER_DESKTOP);
1272 }
1273 }
1274
Adam Cohen72960972014-01-15 18:13:55 -08001275 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1276 // Folders first
1277 allItems.addAll(folders);
1278 // Then shortcuts
1279 allItems.addAll(shortcuts);
1280
1281 // Layout all the folders
1282 for (ContentValues values: allItems) {
1283 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1284 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1285 // Hotseat items and folder items have already had their
1286 // location information set. Nothing to be done here.
1287 continue;
1288 }
1289 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1290 values.put(LauncherSettings.Favorites.CELLX, curX);
1291 values.put(LauncherSettings.Favorites.CELLY, curY);
1292 curX = (curX + 1) % width;
1293 if (curX == 0) {
1294 curY = (curY + 1);
1295 }
1296 // Leave the last row of icons blank on every screen
1297 if (curY == height - 1) {
1298 curScreen = (int) generateNewScreenId();
1299 curY = 0;
1300 }
1301 }
1302
1303 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001304 db.beginTransaction();
1305 try {
Adam Cohen72960972014-01-15 18:13:55 -08001306 for (ContentValues row: allItems) {
1307 if (row == null) continue;
1308 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001309 < 0) {
1310 return;
1311 } else {
1312 count++;
1313 }
1314 }
1315 db.setTransactionSuccessful();
1316 } finally {
1317 db.endTransaction();
1318 }
1319 }
1320
1321 db.beginTransaction();
1322 try {
1323 for (i=0; i<=curScreen; i++) {
1324 final ContentValues values = new ContentValues();
1325 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1326 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1327 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1328 < 0) {
1329 return;
1330 }
1331 }
1332 db.setTransactionSuccessful();
1333 } finally {
1334 db.endTransaction();
1335 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001336
1337 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001338 }
1339 } finally {
1340 c.close();
1341 }
1342 }
1343
Sunny Goyala1365452015-10-01 15:46:24 -07001344 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1345 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001346
1347 // ensure that new screens are created to hold these icons
1348 setFlagJustLoadedOldDb();
1349
1350 // Update max IDs; very important since we just grabbed IDs from another database
1351 mMaxItemId = initializeMaxItemId(db);
1352 mMaxScreenId = initializeMaxScreenId(db);
1353 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1354 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001355 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001356
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001357 /**
1358 * @return the max _id in the provided table.
1359 */
Adam Cohen091440a2015-03-18 14:16:05 -07001360 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001361 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1362 // get the result
1363 long id = -1;
1364 if (c != null && c.moveToNext()) {
1365 id = c.getLong(0);
1366 }
1367 if (c != null) {
1368 c.close();
1369 }
1370
1371 if (id == -1) {
1372 throw new RuntimeException("Error: could not query max id in " + table);
1373 }
1374
1375 return id;
1376 }
1377
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001378 static class SqlArguments {
1379 public final String table;
1380 public final String where;
1381 public final String[] args;
1382
1383 SqlArguments(Uri url, String where, String[] args) {
1384 if (url.getPathSegments().size() == 1) {
1385 this.table = url.getPathSegments().get(0);
1386 this.where = where;
1387 this.args = args;
1388 } else if (url.getPathSegments().size() != 2) {
1389 throw new IllegalArgumentException("Invalid URI: " + url);
1390 } else if (!TextUtils.isEmpty(where)) {
1391 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1392 } else {
1393 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001394 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001395 this.args = null;
1396 }
1397 }
1398
1399 SqlArguments(Uri url) {
1400 if (url.getPathSegments().size() == 1) {
1401 table = url.getPathSegments().get(0);
1402 where = null;
1403 args = null;
1404 } else {
1405 throw new IllegalArgumentException("Invalid URI: " + url);
1406 }
1407 }
1408 }
Adam Cohen72960972014-01-15 18:13:55 -08001409}