blob: 20844ec132e8a2c4c3b8221d6a476d11e97de903 [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 {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final String TAG = "Launcher.LauncherProvider";
69 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
Adam Cohene25af792013-06-06 23:08:25 -070073 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Sunny Goyale5bb7052015-07-27 14:36:07 -070074 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070075
Sunny Goyal18b640c2015-04-17 09:24:01 -070076 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
77 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080078 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070080 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
81
Sunny Goyal383c5072015-06-12 21:18:53 -070082 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070083 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
85 @Override
86 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040087 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080088 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040089 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080090 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 return true;
93 }
94
Winson Chung0b560dd2014-01-21 13:00:26 -080095 public boolean wasNewDbCreated() {
96 return mOpenHelper.wasNewDbCreated();
97 }
98
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
100 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700101 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
114 @Override
115 public Cursor query(Uri uri, String[] projection, String selection,
116 String[] selectionArgs, String sortOrder) {
117
118 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
119 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
120 qb.setTables(args.table);
121
Romain Guy73b979d2009-06-09 12:57:21 -0700122 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
124 result.setNotificationUri(getContext().getContentResolver(), uri);
125
126 return result;
127 }
128
Adam Cohen091440a2015-03-18 14:16:05 -0700129 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700130 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500131 if (values == null) {
132 throw new RuntimeException("Error: attempting to insert null values");
133 }
Adam Cohen71483f42014-05-15 14:04:01 -0700134 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 throw new RuntimeException("Error: attempting to add item without specifying an id");
136 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500137 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 return db.insert(table, nullColumnHack, values);
139 }
140
Sunny Goyald1064182015-08-13 12:08:30 -0700141 private void reloadLauncherIfExternal() {
142 if (Binder.getCallingPid() != Process.myPid()) {
143 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
144 if (app != null) {
145 app.reloadWorkspace();
146 }
147 }
148 }
149
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150 @Override
151 public Uri insert(Uri uri, ContentValues initialValues) {
152 SqlArguments args = new SqlArguments(uri);
153
Sunny Goyald1064182015-08-13 12:08:30 -0700154 // In very limited cases, we support system|signature permission apps to modify the db.
155 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700156 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
157 return null;
158 }
159 }
160
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800161 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400162 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700163 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800164 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165
166 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700167 notifyListeners();
168
Sunny Goyald1064182015-08-13 12:08:30 -0700169 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 return uri;
171 }
172
Adam Cohena043fa82014-07-23 14:49:38 -0700173
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 @Override
175 public int bulkInsert(Uri uri, ContentValues[] values) {
176 SqlArguments args = new SqlArguments(uri);
177
178 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
179 db.beginTransaction();
180 try {
181 int numValues = values.length;
182 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400183 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
185 return 0;
186 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187 }
188 db.setTransactionSuccessful();
189 } finally {
190 db.endTransaction();
191 }
192
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700193 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700194 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 return values.length;
196 }
197
198 @Override
Yura085c8532014-02-11 15:15:29 +0000199 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
200 throws OperationApplicationException {
201 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
202 db.beginTransaction();
203 try {
204 ContentProviderResult[] result = super.applyBatch(operations);
205 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700206 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000207 return result;
208 } finally {
209 db.endTransaction();
210 }
211 }
212
213 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214 public int delete(Uri uri, String selection, String[] selectionArgs) {
215 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
216
217 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
218 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700219 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220
Sunny Goyald1064182015-08-13 12:08:30 -0700221 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222 return count;
223 }
224
225 @Override
226 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
227 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
228
Chris Wren1ada10d2013-09-13 18:01:38 -0400229 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800230 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
231 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700232 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233
Sunny Goyald1064182015-08-13 12:08:30 -0700234 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 return count;
236 }
237
Sunny Goyal7779d622015-06-11 16:18:39 -0700238 @Override
239 public Bundle call(String method, String arg, Bundle extras) {
240 if (Binder.getCallingUid() != Process.myUid()) {
241 return null;
242 }
243
244 switch (method) {
245 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
246 Bundle result = new Bundle();
247 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
248 getContext().getSharedPreferences(
249 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
250 .getBoolean(arg, extras.getBoolean(
251 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
252 return result;
253 }
254 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
255 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
256 getContext().getSharedPreferences(
257 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
258 .edit().putBoolean(arg, value).apply();
259 if (mListener != null) {
260 mListener.onSettingsChanged(arg, value);
261 }
262 Bundle result = new Bundle();
263 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
264 return result;
265 }
266 }
267 return null;
268 }
269
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700270 /**
271 * Deletes any empty folder from the DB.
272 * @return Ids of deleted folders.
273 */
274 public List<Long> deleteEmptyFolders() {
275 ArrayList<Long> folderIds = new ArrayList<Long>();
276 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
277 db.beginTransaction();
278 try {
279 // Select folders whose id do not match any container value.
280 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
281 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
282 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
283 LauncherSettings.Favorites.CONTAINER + " FROM "
284 + TABLE_FAVORITES + ")";
285 Cursor c = db.query(TABLE_FAVORITES,
286 new String[] {LauncherSettings.Favorites._ID},
287 selection, null, null, null, null);
288 while (c.moveToNext()) {
289 folderIds.add(c.getLong(0));
290 }
291 c.close();
292 if (folderIds.size() > 0) {
293 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
294 LauncherSettings.Favorites._ID, folderIds), null);
295 }
296 db.setTransactionSuccessful();
297 } catch (SQLException ex) {
298 Log.e(TAG, ex.getMessage(), ex);
299 folderIds.clear();
300 } finally {
301 db.endTransaction();
302 }
303 return folderIds;
304 }
305
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700306 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400307 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400308 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700309 if (mListener != null) {
310 mListener.onLauncherProviderChange();
311 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 }
313
Adam Cohen091440a2015-03-18 14:16:05 -0700314 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400315 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800316 }
317
Adam Cohendcd297f2013-06-18 13:13:40 -0700318 public long generateNewItemId() {
319 return mOpenHelper.generateNewItemId();
320 }
321
Winson Chungc763c4e2013-07-19 13:49:06 -0700322 public void updateMaxItemId(long id) {
323 mOpenHelper.updateMaxItemId(id);
324 }
325
Adam Cohendcd297f2013-06-18 13:13:40 -0700326 public long generateNewScreenId() {
327 return mOpenHelper.generateNewScreenId();
328 }
329
Brian Muramatsu5524b492012-10-02 16:55:54 -0700330 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700331 * Clears all the data for a fresh start.
332 */
333 synchronized public void createEmptyDB() {
334 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
335 }
336
Sunny Goyal33d44382014-10-16 09:24:19 -0700337 public void clearFlagEmptyDbCreated() {
338 String spKey = LauncherAppState.getSharedPreferencesKey();
339 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
340 .edit()
341 .remove(EMPTY_DATABASE_CREATED)
342 .commit();
343 }
344
Sunny Goyal42de82f2014-09-26 22:09:29 -0700345 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700346 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700347 * 1) From the app restrictions
348 * 2) From a package provided by play store
349 * 3) From a partner configuration APK, already in the system image
350 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700351 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700352 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400353 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700354 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700355
Winson Chungc763c4e2013-07-19 13:49:06 -0700356 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500357 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200358
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700359 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
360 if (loader == null) {
361 loader = AutoInstallsLayout.get(getContext(),
362 mOpenHelper.mAppWidgetHost, mOpenHelper);
363 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700364 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700365 final Partner partner = Partner.get(getContext().getPackageManager());
366 if (partner != null && partner.hasDefaultLayout()) {
367 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700368 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700369 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700370 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700371 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
372 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700373 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700374 }
375 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700376
Sunny Goyal9d219682014-10-23 14:21:02 -0700377 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700378 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700379 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700380 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800381
382 // There might be some partially restored DB items, due to buggy restore logic in
383 // previous versions of launcher.
384 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700385 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700386 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
387 && usingExternallyProvidedLayout) {
388 // Unable to load external layout. Cleanup and load the internal layout.
389 createEmptyDB();
390 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
391 getDefaultLayoutParser());
392 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700393 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700394 }
395 }
396
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700397 /**
398 * Creates workspace loader from an XML resource listed in the app restrictions.
399 *
400 * @return the loader if the restrictions are set and the resource exists; null otherwise.
401 */
402 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
403 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
404 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700405 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700406 return null;
407 }
408
409 Context ctx = getContext();
410 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
411 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700412 if (bundle == null) {
413 return null;
414 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700415
Sunny Goyal35ca8732015-04-06 10:45:31 -0700416 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700417 if (packageName != null) {
418 try {
419 Resources targetResources = ctx.getPackageManager()
420 .getResourcesForApplication(packageName);
421 return AutoInstallsLayout.get(ctx, packageName, targetResources,
422 mOpenHelper.mAppWidgetHost, mOpenHelper);
423 } catch (NameNotFoundException e) {
424 Log.e(TAG, "Target package for restricted profile not found", e);
425 return null;
426 }
427 }
428 return null;
429 }
430
Sunny Goyal9d219682014-10-23 14:21:02 -0700431 private DefaultLayoutParser getDefaultLayoutParser() {
432 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700433 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700434 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
435 mOpenHelper, getContext().getResources(), defaultLayout);
436 }
437
Dan Sandlerd5024042014-01-09 15:01:33 -0500438 public void migrateLauncher2Shortcuts() {
439 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400440 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500441 }
442
Sunny Goyal08f72612015-01-05 13:41:43 -0800443 public void updateFolderItemsRank() {
444 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
445 }
446
Sunny Goyal5c97f512015-05-19 16:03:28 -0700447 public void convertShortcutsToLauncherActivities() {
448 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
449 }
450
451
Dan Sandlerd5024042014-01-09 15:01:33 -0500452 public void deleteDatabase() {
453 // Are you sure? (y/n)
454 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500455 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500456 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500457 if (dbFile.exists()) {
458 SQLiteDatabase.deleteDatabase(dbFile);
459 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500460 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700461 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500462 }
463
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700464 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700466 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700467 private long mMaxItemId = -1;
468 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469
Winson Chung0b560dd2014-01-21 13:00:26 -0800470 private boolean mNewDbCreated = false;
471
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700472 @Thunk LauncherProviderChangeListener mListener;
473
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100475 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800476 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700477 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700478
479 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
480 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700481 if (mMaxItemId == -1) {
482 mMaxItemId = initializeMaxItemId(getWritableDatabase());
483 }
484 if (mMaxScreenId == -1) {
485 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700486 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800487 }
488
Winson Chung0b560dd2014-01-21 13:00:26 -0800489 public boolean wasNewDbCreated() {
490 return mNewDbCreated;
491 }
492
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800493 @Override
494 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800495 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700496
Adam Cohendcd297f2013-06-18 13:13:40 -0700497 mMaxItemId = 1;
498 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800499 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700500
Kenny Guyed131872014-04-30 03:02:21 +0100501 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
502 long userSerialNumber = userManager.getSerialNumberForUser(
503 UserHandleCompat.myUserHandle());
504
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800505 db.execSQL("CREATE TABLE favorites (" +
506 "_id INTEGER PRIMARY KEY," +
507 "title TEXT," +
508 "intent TEXT," +
509 "container INTEGER," +
510 "screen INTEGER," +
511 "cellX INTEGER," +
512 "cellY INTEGER," +
513 "spanX INTEGER," +
514 "spanY INTEGER," +
515 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700516 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800517 "isShortcut INTEGER," +
518 "iconType INTEGER," +
519 "iconPackage TEXT," +
520 "iconResource TEXT," +
521 "icon BLOB," +
522 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400523 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400524 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500525 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100526 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800527 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700528 "rank INTEGER NOT NULL DEFAULT 0," +
529 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700531 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800532
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700533 // Database was just created, so wipe any previous widgets
534 if (mAppWidgetHost != null) {
535 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700536
537 /**
538 * Send notification that we've deleted the {@link AppWidgetHost},
539 * probably as part of the initial database creation. The receiver may
540 * want to re-call {@link AppWidgetHost#startListening()} to ensure
541 * callbacks are correctly set.
542 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700543 new MainThreadExecutor().execute(new Runnable() {
544
545 @Override
546 public void run() {
547 if (mListener != null) {
548 mListener.onAppWidgetHostReset();
549 }
550 }
551 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700553
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800554 // Fresh and clean launcher DB.
555 mMaxItemId = initializeMaxItemId(db);
556 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700557
558 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700559 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800560 }
561
Adam Cohendcd297f2013-06-18 13:13:40 -0700562 private void addWorkspacesTable(SQLiteDatabase db) {
563 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800564 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400565 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
566 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700567 ");");
568 }
569
Adam Cohen119285e2014-04-02 16:59:08 -0700570 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700571 // Delete items directly on the workspace who's screen id doesn't exist
572 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
573 // AND container = -100"
574 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
575 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700576 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700577 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
578 " AND " +
579 LauncherSettings.Favorites.CONTAINER + " = " +
580 LauncherSettings.Favorites.CONTAINER_DESKTOP;
581 db.execSQL(removeOrphanedDesktopItems);
582
583 // Delete items contained in folders which no longer exist (after above statement)
584 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
585 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
586 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
587 " WHERE " +
588 LauncherSettings.Favorites.CONTAINER + " <> " +
589 LauncherSettings.Favorites.CONTAINER_DESKTOP +
590 " AND "
591 + LauncherSettings.Favorites.CONTAINER + " <> " +
592 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
593 " AND "
594 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
595 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
596 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
597 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
598 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700599 }
600
Winson Chungc763c4e2013-07-19 13:49:06 -0700601 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400602 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700603 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800604 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700605 }
606
Winson Chungc763c4e2013-07-19 13:49:06 -0700607 private void setFlagEmptyDbCreated() {
608 String spKey = LauncherAppState.getSharedPreferencesKey();
609 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800610 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700611 }
612
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613 @Override
614 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700615 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800616 switch (oldVersion) {
617 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800618 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800619 case 12: {
620 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
621 // to persist workspace screens and their relative order.
622 mMaxScreenId = 0;
623 addWorkspacesTable(db);
624 }
625 case 13: {
626 db.beginTransaction();
627 try {
628 // Insert new column for holding widget provider name
629 db.execSQL("ALTER TABLE favorites " +
630 "ADD COLUMN appWidgetProvider TEXT;");
631 db.setTransactionSuccessful();
632 } catch (SQLException ex) {
633 Log.e(TAG, ex.getMessage(), ex);
634 // Old version remains, which means we wipe old data
635 break;
636 } finally {
637 db.endTransaction();
638 }
639 }
640 case 14: {
641 db.beginTransaction();
642 try {
643 // Insert new column for holding update timestamp
644 db.execSQL("ALTER TABLE favorites " +
645 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
646 db.execSQL("ALTER TABLE workspaceScreens " +
647 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
648 db.setTransactionSuccessful();
649 } catch (SQLException ex) {
650 Log.e(TAG, ex.getMessage(), ex);
651 // Old version remains, which means we wipe old data
652 break;
653 } finally {
654 db.endTransaction();
655 }
656 }
657 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700658 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 // Old version remains, which means we wipe old data
660 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800661 }
662 }
663 case 16: {
664 // We use the db version upgrade here to identify users who may not have seen
665 // clings yet (because they weren't available), but for whom the clings are now
666 // available (tablet users). Because one of the possible cling flows (migration)
667 // is very destructive (wipes out workspaces), we want to prevent this from showing
668 // until clear data. We do so by marking that the clings have been shown.
669 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
670 }
671 case 17: {
672 // No-op
673 }
674 case 18: {
675 // Due to a data loss bug, some users may have items associated with screen ids
676 // which no longer exist. Since this can cause other problems, and since the user
677 // will never see these items anyway, we use database upgrade as an opportunity to
678 // clean things up.
679 removeOrphanedItems(db);
680 }
681 case 19: {
682 // Add userId column
683 if (!addProfileColumn(db)) {
684 // Old version remains, which means we wipe old data
685 break;
686 }
687 }
688 case 20:
689 if (!updateFolderItemsRank(db, true)) {
690 break;
691 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800692 case 21:
693 // Recreate workspace table with screen id a primary key
694 if (!recreateWorkspaceTable(db)) {
695 break;
696 }
697 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700698 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
699 // Old version remains, which means we wipe old data
700 break;
701 }
702 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700703 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700704 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700705 case 24:
706 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700707 case 25:
708 convertShortcutsToLauncherActivities(db);
709 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800710 // DB Upgraded successfully
711 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400712 }
713 }
714
Sunny Goyala2cc6242015-01-14 14:23:02 -0800715 // DB was not upgraded
716 Log.w(TAG, "Destroying all old data.");
717 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800719
Adam Cohen9b1d0622014-05-21 19:01:57 -0700720 @Override
721 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
722 // This shouldn't happen -- throw our hands up in the air and start over.
723 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
724 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700725 createEmptyDB(db);
726 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700727
Sunny Goyal42de82f2014-09-26 22:09:29 -0700728 /**
729 * Clears all the data for a fresh start.
730 */
731 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700732 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
733 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
734 onCreate(db);
735 }
736
Sunny Goyald2f38192015-02-25 10:46:34 -0800737 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700738 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
739 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
740 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700741 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700742 db.beginTransaction();
743 Cursor c = null;
744 SQLiteStatement updateStmt = null;
745
746 try {
747 // Only consider the primary user as other users can't have a shortcut.
748 long userSerial = UserManagerCompat.getInstance(mContext)
749 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
750 c = db.query(TABLE_FAVORITES, new String[] {
751 Favorites._ID,
752 Favorites.INTENT,
753 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
754 null, null, null, null);
755
756 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
757 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
758
759 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
760 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
761
762 while (c.moveToNext()) {
763 String intentDescription = c.getString(intentIndex);
764 Intent intent;
765 try {
766 intent = Intent.parseUri(intentDescription, 0);
767 } catch (URISyntaxException e) {
768 Log.e(TAG, "Unable to parse intent", e);
769 continue;
770 }
771
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700772 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700773 continue;
774 }
775
776 long id = c.getLong(idIndex);
777 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700778 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700779 }
780 db.setTransactionSuccessful();
781 } catch (SQLException ex) {
782 Log.w(TAG, "Error deduping shortcuts", ex);
783 } finally {
784 db.endTransaction();
785 if (c != null) {
786 c.close();
787 }
788 if (updateStmt != null) {
789 updateStmt.close();
790 }
791 }
792 }
793
794 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800795 * Recreates workspace table and migrates data to the new table.
796 */
797 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
798 db.beginTransaction();
799 try {
800 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
801 new String[] {LauncherSettings.WorkspaceScreens._ID},
802 null, null, null, null,
803 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
804 ArrayList<Long> sortedIDs = new ArrayList<Long>();
805 long maxId = 0;
806 try {
807 while (c.moveToNext()) {
808 Long id = c.getLong(0);
809 if (!sortedIDs.contains(id)) {
810 sortedIDs.add(id);
811 maxId = Math.max(maxId, id);
812 }
813 }
814 } finally {
815 c.close();
816 }
817
818 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
819 addWorkspacesTable(db);
820
821 // Add all screen ids back
822 int total = sortedIDs.size();
823 for (int i = 0; i < total; i++) {
824 ContentValues values = new ContentValues();
825 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
826 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
827 addModifiedTime(values);
828 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
829 }
830 db.setTransactionSuccessful();
831 mMaxScreenId = maxId;
832 } catch (SQLException ex) {
833 // Old version remains, which means we wipe old data
834 Log.e(TAG, ex.getMessage(), ex);
835 return false;
836 } finally {
837 db.endTransaction();
838 }
839 return true;
840 }
841
Adam Cohen091440a2015-03-18 14:16:05 -0700842 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800843 db.beginTransaction();
844 try {
845 if (addRankColumn) {
846 // Insert new column for holding rank
847 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
848 }
849
850 // Get a map for folder ID to folder width
851 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
852 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
853 + " GROUP BY container;",
854 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
855
856 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800857 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
858 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800859 new Object[] {c.getLong(1) + 1, c.getLong(0)});
860 }
861
862 c.close();
863 db.setTransactionSuccessful();
864 } catch (SQLException ex) {
865 // Old version remains, which means we wipe old data
866 Log.e(TAG, ex.getMessage(), ex);
867 return false;
868 } finally {
869 db.endTransaction();
870 }
871 return true;
872 }
873
Kenny Guyed131872014-04-30 03:02:21 +0100874 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700875 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
876 // Default to the serial number of this user, for older
877 // shortcuts.
878 long userSerialNumber = userManager.getSerialNumberForUser(
879 UserHandleCompat.myUserHandle());
880 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
881 }
882
883 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100884 db.beginTransaction();
885 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700886 db.execSQL("ALTER TABLE favorites ADD COLUMN "
887 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100890 Log.e(TAG, ex.getMessage(), ex);
891 return false;
892 } finally {
893 db.endTransaction();
894 }
895 return true;
896 }
897
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700898 // Generates a new ID to use for an object in your database. This method should be only
899 // called from the main UI thread. As an exception, we do call it when we call the
900 // constructor from the worker thread; however, this doesn't extend until after the
901 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
902 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700903 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700904 public long generateNewItemId() {
905 if (mMaxItemId < 0) {
906 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700907 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700908 mMaxItemId += 1;
909 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700910 }
911
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700912 @Override
913 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
914 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
915 }
916
Winson Chungc763c4e2013-07-19 13:49:06 -0700917 public void updateMaxItemId(long id) {
918 mMaxItemId = id + 1;
919 }
920
Chris Wren5dee7af2013-12-20 17:22:11 -0500921 public void checkId(String table, ContentValues values) {
922 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
923 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
924 mMaxScreenId = Math.max(id, mMaxScreenId);
925 } else {
926 mMaxItemId = Math.max(id, mMaxItemId);
927 }
928 }
929
Adam Cohendcd297f2013-06-18 13:13:40 -0700930 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800931 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700932 }
933
934 // Generates a new ID to use for an workspace screen in your database. This method
935 // should be only called from the main UI thread. As an exception, we do call it when we
936 // call the constructor from the worker thread; however, this doesn't extend until after the
937 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
938 // after that point
939 public long generateNewScreenId() {
940 if (mMaxScreenId < 0) {
941 throw new RuntimeException("Error: max screen id was not initialized");
942 }
943 mMaxScreenId += 1;
944 return mMaxScreenId;
945 }
946
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800948 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800949 }
950
Adam Cohen091440a2015-03-18 14:16:05 -0700951 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700952 // 1. Ensure that externally added items have a valid item id
953 long id = generateNewItemId();
954 values.put(LauncherSettings.Favorites._ID, id);
955
956 // 2. In the case of an app widget, and if no app widget id is specified, we
957 // attempt allocate and bind the widget.
958 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
959 if (itemType != null &&
960 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
961 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
962
963 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
964 ComponentName cn = ComponentName.unflattenFromString(
965 values.getAsString(Favorites.APPWIDGET_PROVIDER));
966
967 if (cn != null) {
968 try {
969 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700970 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700971 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700972 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700973 }
974 } catch (RuntimeException e) {
975 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700976 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700977 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700978 } else {
979 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700980 }
981 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700982
983 // Add screen id if not present
984 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
985 if (!addScreenIdIfNecessary(screenId)) {
986 return false;
987 }
Adam Cohena043fa82014-07-23 14:49:38 -0700988 return true;
989 }
990
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700991 // Returns true of screen id exists, or if successfully added
992 private boolean addScreenIdIfNecessary(long screenId) {
993 if (!hasScreenId(screenId)) {
994 int rank = getMaxScreenRank() + 1;
995
996 ContentValues v = new ContentValues();
997 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
998 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
999 if (dbInsertAndCheck(this, getWritableDatabase(),
1000 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1001 return false;
1002 }
1003 }
1004 return true;
1005 }
1006
1007 private boolean hasScreenId(long screenId) {
1008 SQLiteDatabase db = getWritableDatabase();
1009 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1010 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1011 if (c != null) {
1012 int count = c.getCount();
1013 c.close();
1014 return count > 0;
1015 } else {
1016 return false;
1017 }
1018 }
1019
1020 private int getMaxScreenRank() {
1021 SQLiteDatabase db = getWritableDatabase();
1022 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1023 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1024
1025 // get the result
1026 final int maxRankIndex = 0;
1027 int rank = -1;
1028 if (c != null && c.moveToNext()) {
1029 rank = c.getInt(maxRankIndex);
1030 }
1031 if (c != null) {
1032 c.close();
1033 }
1034
1035 return rank;
1036 }
1037
Adam Cohen091440a2015-03-18 14:16:05 -07001038 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001039 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001040 // TODO: Use multiple loaders with fall-back and transaction.
1041 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001042
1043 // Add the screens specified by the items above
1044 Collections.sort(screenIds);
1045 int rank = 0;
1046 ContentValues values = new ContentValues();
1047 for (Long id : screenIds) {
1048 values.clear();
1049 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1050 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1051 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1052 throw new RuntimeException("Failed initialize screen table"
1053 + "from default layout");
1054 }
1055 rank++;
1056 }
1057
1058 // Ensure that the max ids are initialized
1059 mMaxItemId = initializeMaxItemId(db);
1060 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001061
Adam Cohen71483f42014-05-15 14:04:01 -07001062 return count;
1063 }
1064
Adam Cohen091440a2015-03-18 14:16:05 -07001065 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001066 final ContentResolver resolver = mContext.getContentResolver();
1067 Cursor c = null;
1068 int count = 0;
1069 int curScreen = 0;
1070
1071 try {
1072 c = resolver.query(uri, null, null, null, "title ASC");
1073 } catch (Exception e) {
1074 // Ignore
1075 }
1076
Dan Sandlerd5024042014-01-09 15:01:33 -05001077 // We already have a favorites database in the old provider
1078 if (c != null) {
1079 try {
1080 if (c.getCount() > 0) {
1081 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1082 final int intentIndex
1083 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1084 final int titleIndex
1085 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1086 final int iconTypeIndex
1087 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1088 final int iconIndex
1089 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1090 final int iconPackageIndex
1091 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1092 final int iconResourceIndex
1093 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1094 final int containerIndex
1095 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1096 final int itemTypeIndex
1097 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1098 final int screenIndex
1099 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1100 final int cellXIndex
1101 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1102 final int cellYIndex
1103 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1104 final int uriIndex
1105 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1106 final int displayModeIndex
1107 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001108 final int profileIndex
1109 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001110
1111 int i = 0;
1112 int curX = 0;
1113 int curY = 0;
1114
1115 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001116 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1117 final int width = (int) profile.numColumns;
1118 final int height = (int) profile.numRows;
1119 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001120
1121 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1122
Adam Cohen72960972014-01-15 18:13:55 -08001123 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1124 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001125 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001126
1127 while (c.moveToNext()) {
1128 final int itemType = c.getInt(itemTypeIndex);
1129 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1130 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1131 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1132 continue;
1133 }
1134
1135 final int cellX = c.getInt(cellXIndex);
1136 final int cellY = c.getInt(cellYIndex);
1137 final int screen = c.getInt(screenIndex);
1138 int container = c.getInt(containerIndex);
1139 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001140
1141 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1142 UserHandleCompat userHandle;
1143 final long userSerialNumber;
1144 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1145 userSerialNumber = c.getInt(profileIndex);
1146 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1147 } else {
1148 // Default to the serial number of this user, for older
1149 // shortcuts.
1150 userHandle = UserHandleCompat.myUserHandle();
1151 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1152 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001153
1154 if (userHandle == null) {
1155 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1156 continue;
1157 }
1158
Dan Sandlerd5024042014-01-09 15:01:33 -05001159 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001160 + c.getString(titleIndex) + "\" ("
1161 + cellX + "," + cellY + "@"
1162 + LauncherSettings.Favorites.containerToString(container)
1163 + "/" + screen
1164 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001165
1166 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001167
1168 final Intent intent;
1169 final ComponentName cn;
1170 try {
1171 intent = Intent.parseUri(intentStr, 0);
1172 } catch (URISyntaxException e) {
1173 // bogus intent?
1174 Launcher.addDumpLog(TAG,
1175 "skipping invalid intent uri", true);
1176 continue;
1177 }
1178
1179 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001180 if (TextUtils.isEmpty(intentStr)) {
1181 // no intent? no icon
1182 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1183 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.
Adam Cohen72960972014-01-15 18:13:55 -08001188 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001189 "no longer exists.", true);
1190 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001191 } else if (container ==
1192 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1193 // Dedupe icons directly on the workspace
1194
Adam Cohen556f6132014-01-15 15:18:08 -08001195 // Canonicalize
1196 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001197 // does not, so we clear that out to keep them the same.
1198 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001199 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001200 int flags = intent.getFlags();
1201 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001202 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001203 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001204 if (seenIntents.contains(key)) {
1205 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001206 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001207 } else {
1208 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001209 }
1210 }
1211 }
1212
1213 ContentValues values = new ContentValues(c.getColumnCount());
1214 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1215 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1216 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1217 values.put(LauncherSettings.Favorites.ICON_TYPE,
1218 c.getInt(iconTypeIndex));
1219 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1220 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1221 c.getString(iconPackageIndex));
1222 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1223 c.getString(iconResourceIndex));
1224 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1225 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1226 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1227 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1228 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001229 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001230
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001231 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1232 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001233 }
1234
1235 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1236 // In a folder or in the hotseat, preserve position
1237 values.put(LauncherSettings.Favorites.SCREEN, screen);
1238 values.put(LauncherSettings.Favorites.CELLX, cellX);
1239 values.put(LauncherSettings.Favorites.CELLY, cellY);
1240 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001241 // For items contained directly on one of the workspace screen,
1242 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001243 }
1244
1245 values.put(LauncherSettings.Favorites.CONTAINER, container);
1246
Adam Cohen72960972014-01-15 18:13:55 -08001247 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1248 shortcuts.add(values);
1249 } else {
1250 folders.add(values);
1251 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001252 }
1253
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001254 // Now that we have all the hotseat icons, let's go through them left-right
1255 // and assign valid locations for them in the new hotseat
1256 final int N = hotseat.size();
1257 for (int idx=0; idx<N; idx++) {
1258 int hotseatX = hotseat.keyAt(idx);
1259 ContentValues values = hotseat.valueAt(idx);
1260
Adam Cohen2e6da152015-05-06 11:42:25 -07001261 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001262 // let's drop this in the next available hole in the hotseat
1263 while (++hotseatX < hotseatWidth) {
1264 if (hotseat.get(hotseatX) == null) {
1265 // found a spot! move it here
1266 values.put(LauncherSettings.Favorites.SCREEN,
1267 hotseatX);
1268 break;
1269 }
1270 }
1271 }
1272 if (hotseatX >= hotseatWidth) {
1273 // no room for you in the hotseat? it's off to the desktop with you
1274 values.put(LauncherSettings.Favorites.CONTAINER,
1275 Favorites.CONTAINER_DESKTOP);
1276 }
1277 }
1278
Adam Cohen72960972014-01-15 18:13:55 -08001279 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1280 // Folders first
1281 allItems.addAll(folders);
1282 // Then shortcuts
1283 allItems.addAll(shortcuts);
1284
1285 // Layout all the folders
1286 for (ContentValues values: allItems) {
1287 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1288 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1289 // Hotseat items and folder items have already had their
1290 // location information set. Nothing to be done here.
1291 continue;
1292 }
1293 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1294 values.put(LauncherSettings.Favorites.CELLX, curX);
1295 values.put(LauncherSettings.Favorites.CELLY, curY);
1296 curX = (curX + 1) % width;
1297 if (curX == 0) {
1298 curY = (curY + 1);
1299 }
1300 // Leave the last row of icons blank on every screen
1301 if (curY == height - 1) {
1302 curScreen = (int) generateNewScreenId();
1303 curY = 0;
1304 }
1305 }
1306
1307 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001308 db.beginTransaction();
1309 try {
Adam Cohen72960972014-01-15 18:13:55 -08001310 for (ContentValues row: allItems) {
1311 if (row == null) continue;
1312 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001313 < 0) {
1314 return;
1315 } else {
1316 count++;
1317 }
1318 }
1319 db.setTransactionSuccessful();
1320 } finally {
1321 db.endTransaction();
1322 }
1323 }
1324
1325 db.beginTransaction();
1326 try {
1327 for (i=0; i<=curScreen; i++) {
1328 final ContentValues values = new ContentValues();
1329 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1330 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1331 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1332 < 0) {
1333 return;
1334 }
1335 }
1336 db.setTransactionSuccessful();
1337 } finally {
1338 db.endTransaction();
1339 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001340
1341 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001342 }
1343 } finally {
1344 c.close();
1345 }
1346 }
1347
1348 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1349 + (curScreen+1) + " screens", true);
1350
1351 // ensure that new screens are created to hold these icons
1352 setFlagJustLoadedOldDb();
1353
1354 // Update max IDs; very important since we just grabbed IDs from another database
1355 mMaxItemId = initializeMaxItemId(db);
1356 mMaxScreenId = initializeMaxScreenId(db);
1357 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1358 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001359 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001360
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001361 /**
1362 * @return the max _id in the provided table.
1363 */
Adam Cohen091440a2015-03-18 14:16:05 -07001364 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001365 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1366 // get the result
1367 long id = -1;
1368 if (c != null && c.moveToNext()) {
1369 id = c.getLong(0);
1370 }
1371 if (c != null) {
1372 c.close();
1373 }
1374
1375 if (id == -1) {
1376 throw new RuntimeException("Error: could not query max id in " + table);
1377 }
1378
1379 return id;
1380 }
1381
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001382 static class SqlArguments {
1383 public final String table;
1384 public final String where;
1385 public final String[] args;
1386
1387 SqlArguments(Uri url, String where, String[] args) {
1388 if (url.getPathSegments().size() == 1) {
1389 this.table = url.getPathSegments().get(0);
1390 this.where = where;
1391 this.args = args;
1392 } else if (url.getPathSegments().size() != 2) {
1393 throw new IllegalArgumentException("Invalid URI: " + url);
1394 } else if (!TextUtils.isEmpty(where)) {
1395 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1396 } else {
1397 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001398 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001399 this.args = null;
1400 }
1401 }
1402
1403 SqlArguments(Uri url) {
1404 if (url.getPathSegments().size() == 1) {
1405 table = url.getPathSegments().get(0);
1406 where = null;
1407 args = null;
1408 } else {
1409 throw new IllegalArgumentException("Invalid URI: " + url);
1410 }
1411 }
1412 }
Adam Cohen72960972014-01-15 18:13:55 -08001413}