blob: 9b52a80c9958f69da9edbc28d13e2265571ab294 [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";
Chris Wrene523e702013-10-09 10:36:55 -040074 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
Adam Cohena043fa82014-07-23 14:49:38 -070080 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
81
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070082 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
83
Anjali Koppal67e7cae2014-03-13 12:14:12 -070084 private LauncherProviderChangeListener mListener;
85
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070086 /**
Romain Guy73b979d2009-06-09 12:57:21 -070087 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070088 * {@link AppWidgetHost#deleteHost()} is called during database creation.
89 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
90 */
91 static final Uri CONTENT_APPWIDGET_RESET_URI =
92 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070093
Sunny Goyal316490e2015-06-02 09:38:28 -070094 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
96 @Override
97 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040098 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080099 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400100 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -0800101 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -0400102 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 return true;
104 }
105
Winson Chung0b560dd2014-01-21 13:00:26 -0800106 public boolean wasNewDbCreated() {
107 return mOpenHelper.wasNewDbCreated();
108 }
109
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700110 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
111 mListener = listener;
112 }
113
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114 @Override
115 public String getType(Uri uri) {
116 SqlArguments args = new SqlArguments(uri, null, null);
117 if (TextUtils.isEmpty(args.where)) {
118 return "vnd.android.cursor.dir/" + args.table;
119 } else {
120 return "vnd.android.cursor.item/" + args.table;
121 }
122 }
123
124 @Override
125 public Cursor query(Uri uri, String[] projection, String selection,
126 String[] selectionArgs, String sortOrder) {
127
128 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
129 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
130 qb.setTables(args.table);
131
Romain Guy73b979d2009-06-09 12:57:21 -0700132 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
134 result.setNotificationUri(getContext().getContentResolver(), uri);
135
136 return result;
137 }
138
Adam Cohen091440a2015-03-18 14:16:05 -0700139 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500141 if (values == null) {
142 throw new RuntimeException("Error: attempting to insert null values");
143 }
Adam Cohen71483f42014-05-15 14:04:01 -0700144 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 throw new RuntimeException("Error: attempting to add item without specifying an id");
146 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500147 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 return db.insert(table, nullColumnHack, values);
149 }
150
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800151 @Override
152 public Uri insert(Uri uri, ContentValues initialValues) {
153 SqlArguments args = new SqlArguments(uri);
154
Adam Cohena043fa82014-07-23 14:49:38 -0700155 // In very limited cases, we support system|signature permission apps to add to the db
156 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700157 final boolean isExternalAll = externalAdd != null && "true".equals(externalAdd);
158 if (isExternalAll) {
Adam Cohena043fa82014-07-23 14:49:38 -0700159 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
160 return null;
161 }
162 }
163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400165 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700166 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800167 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168
169 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700170 notifyListeners();
171
172 if (isExternalAll) {
173 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
174 if (app != null) {
175 app.reloadWorkspace();
176 }
177 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
179 return uri;
180 }
181
Adam Cohena043fa82014-07-23 14:49:38 -0700182
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183 @Override
184 public int bulkInsert(Uri uri, ContentValues[] values) {
185 SqlArguments args = new SqlArguments(uri);
186
187 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
188 db.beginTransaction();
189 try {
190 int numValues = values.length;
191 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400192 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700193 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
194 return 0;
195 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196 }
197 db.setTransactionSuccessful();
198 } finally {
199 db.endTransaction();
200 }
201
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700202 notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 return values.length;
204 }
205
206 @Override
Yura085c8532014-02-11 15:15:29 +0000207 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
208 throws OperationApplicationException {
209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
210 db.beginTransaction();
211 try {
212 ContentProviderResult[] result = super.applyBatch(operations);
213 db.setTransactionSuccessful();
214 return result;
215 } finally {
216 db.endTransaction();
217 }
218 }
219
220 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 public int delete(Uri uri, String selection, String[] selectionArgs) {
222 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
223
224 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
225 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700226 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227
228 return count;
229 }
230
231 @Override
232 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
233 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
234
Chris Wren1ada10d2013-09-13 18:01:38 -0400235 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
237 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700238 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239
240 return count;
241 }
242
Sunny Goyal7779d622015-06-11 16:18:39 -0700243 @Override
244 public Bundle call(String method, String arg, Bundle extras) {
245 if (Binder.getCallingUid() != Process.myUid()) {
246 return null;
247 }
248
249 switch (method) {
250 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
251 Bundle result = new Bundle();
252 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
253 getContext().getSharedPreferences(
254 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
255 .getBoolean(arg, extras.getBoolean(
256 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
257 return result;
258 }
259 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
260 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
261 getContext().getSharedPreferences(
262 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
263 .edit().putBoolean(arg, value).apply();
264 if (mListener != null) {
265 mListener.onSettingsChanged(arg, value);
266 }
267 Bundle result = new Bundle();
268 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
269 return result;
270 }
271 }
272 return null;
273 }
274
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700275 /**
276 * Deletes any empty folder from the DB.
277 * @return Ids of deleted folders.
278 */
279 public List<Long> deleteEmptyFolders() {
280 ArrayList<Long> folderIds = new ArrayList<Long>();
281 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
282 db.beginTransaction();
283 try {
284 // Select folders whose id do not match any container value.
285 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
286 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
287 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
288 LauncherSettings.Favorites.CONTAINER + " FROM "
289 + TABLE_FAVORITES + ")";
290 Cursor c = db.query(TABLE_FAVORITES,
291 new String[] {LauncherSettings.Favorites._ID},
292 selection, null, null, null, null);
293 while (c.moveToNext()) {
294 folderIds.add(c.getLong(0));
295 }
296 c.close();
297 if (folderIds.size() > 0) {
298 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
299 LauncherSettings.Favorites._ID, folderIds), null);
300 }
301 db.setTransactionSuccessful();
302 } catch (SQLException ex) {
303 Log.e(TAG, ex.getMessage(), ex);
304 folderIds.clear();
305 } finally {
306 db.endTransaction();
307 }
308 return folderIds;
309 }
310
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700311 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400313 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700314 if (mListener != null) {
315 mListener.onLauncherProviderChange();
316 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400317 }
318
Adam Cohen091440a2015-03-18 14:16:05 -0700319 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400320 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800321 }
322
Adam Cohendcd297f2013-06-18 13:13:40 -0700323 public long generateNewItemId() {
324 return mOpenHelper.generateNewItemId();
325 }
326
Winson Chungc763c4e2013-07-19 13:49:06 -0700327 public void updateMaxItemId(long id) {
328 mOpenHelper.updateMaxItemId(id);
329 }
330
Adam Cohendcd297f2013-06-18 13:13:40 -0700331 public long generateNewScreenId() {
332 return mOpenHelper.generateNewScreenId();
333 }
334
Brian Muramatsu5524b492012-10-02 16:55:54 -0700335 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700336 * Clears all the data for a fresh start.
337 */
338 synchronized public void createEmptyDB() {
339 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
340 }
341
Sunny Goyal33d44382014-10-16 09:24:19 -0700342 public void clearFlagEmptyDbCreated() {
343 String spKey = LauncherAppState.getSharedPreferencesKey();
344 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
345 .edit()
346 .remove(EMPTY_DATABASE_CREATED)
347 .commit();
348 }
349
Sunny Goyal42de82f2014-09-26 22:09:29 -0700350 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700351 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700352 * 1) From the app restrictions
353 * 2) From a package provided by play store
354 * 3) From a partner configuration APK, already in the system image
355 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700356 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700357 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400358 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700359 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700360
Winson Chungc763c4e2013-07-19 13:49:06 -0700361 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500362 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200363
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700364 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
365 if (loader == null) {
366 loader = AutoInstallsLayout.get(getContext(),
367 mOpenHelper.mAppWidgetHost, mOpenHelper);
368 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700369 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700370 final Partner partner = Partner.get(getContext().getPackageManager());
371 if (partner != null && partner.hasDefaultLayout()) {
372 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700373 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700374 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700375 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700376 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
377 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700378 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700379 }
380 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700381
Sunny Goyal9d219682014-10-23 14:21:02 -0700382 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700383 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700384 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700385 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800386
387 // There might be some partially restored DB items, due to buggy restore logic in
388 // previous versions of launcher.
389 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700390 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700391 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
392 && usingExternallyProvidedLayout) {
393 // Unable to load external layout. Cleanup and load the internal layout.
394 createEmptyDB();
395 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
396 getDefaultLayoutParser());
397 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700398 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700399 }
400 }
401
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700402 /**
403 * Creates workspace loader from an XML resource listed in the app restrictions.
404 *
405 * @return the loader if the restrictions are set and the resource exists; null otherwise.
406 */
407 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
408 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
409 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
410 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
411 return null;
412 }
413
414 Context ctx = getContext();
415 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
416 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700417 if (bundle == null) {
418 return null;
419 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700420
Sunny Goyal35ca8732015-04-06 10:45:31 -0700421 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700422 if (packageName != null) {
423 try {
424 Resources targetResources = ctx.getPackageManager()
425 .getResourcesForApplication(packageName);
426 return AutoInstallsLayout.get(ctx, packageName, targetResources,
427 mOpenHelper.mAppWidgetHost, mOpenHelper);
428 } catch (NameNotFoundException e) {
429 Log.e(TAG, "Target package for restricted profile not found", e);
430 return null;
431 }
432 }
433 return null;
434 }
435
Sunny Goyal9d219682014-10-23 14:21:02 -0700436 private DefaultLayoutParser getDefaultLayoutParser() {
437 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700438 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700439 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
440 mOpenHelper, getContext().getResources(), defaultLayout);
441 }
442
Dan Sandlerd5024042014-01-09 15:01:33 -0500443 public void migrateLauncher2Shortcuts() {
444 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400445 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500446 }
447
Sunny Goyal08f72612015-01-05 13:41:43 -0800448 public void updateFolderItemsRank() {
449 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
450 }
451
Sunny Goyal5c97f512015-05-19 16:03:28 -0700452 public void convertShortcutsToLauncherActivities() {
453 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
454 }
455
456
Dan Sandlerd5024042014-01-09 15:01:33 -0500457 public void deleteDatabase() {
458 // Are you sure? (y/n)
459 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500460 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500461 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500462 if (dbFile.exists()) {
463 SQLiteDatabase.deleteDatabase(dbFile);
464 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500465 mOpenHelper = new DatabaseHelper(getContext());
466 }
467
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700468 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700470 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700471 private long mMaxItemId = -1;
472 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800473
Winson Chung0b560dd2014-01-21 13:00:26 -0800474 private boolean mNewDbCreated = false;
475
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800476 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100477 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800478 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700479 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700480
481 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
482 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700483 if (mMaxItemId == -1) {
484 mMaxItemId = initializeMaxItemId(getWritableDatabase());
485 }
486 if (mMaxScreenId == -1) {
487 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700488 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800489 }
490
Winson Chung0b560dd2014-01-21 13:00:26 -0800491 public boolean wasNewDbCreated() {
492 return mNewDbCreated;
493 }
494
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700495 /**
496 * Send notification that we've deleted the {@link AppWidgetHost},
497 * probably as part of the initial database creation. The receiver may
498 * want to re-call {@link AppWidgetHost#startListening()} to ensure
499 * callbacks are correctly set.
500 */
501 private void sendAppWidgetResetNotify() {
502 final ContentResolver resolver = mContext.getContentResolver();
503 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
504 }
505
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800506 @Override
507 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800508 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700509
Adam Cohendcd297f2013-06-18 13:13:40 -0700510 mMaxItemId = 1;
511 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800512 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700513
Kenny Guyed131872014-04-30 03:02:21 +0100514 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
515 long userSerialNumber = userManager.getSerialNumberForUser(
516 UserHandleCompat.myUserHandle());
517
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 db.execSQL("CREATE TABLE favorites (" +
519 "_id INTEGER PRIMARY KEY," +
520 "title TEXT," +
521 "intent TEXT," +
522 "container INTEGER," +
523 "screen INTEGER," +
524 "cellX INTEGER," +
525 "cellY INTEGER," +
526 "spanX INTEGER," +
527 "spanY INTEGER," +
528 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700529 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 "isShortcut INTEGER," +
531 "iconType INTEGER," +
532 "iconPackage TEXT," +
533 "iconResource TEXT," +
534 "icon BLOB," +
535 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400536 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400537 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500538 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100539 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800540 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700541 "rank INTEGER NOT NULL DEFAULT 0," +
542 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800543 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700544 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700546 // Database was just created, so wipe any previous widgets
547 if (mAppWidgetHost != null) {
548 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700549 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700551
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800552 // Fresh and clean launcher DB.
553 mMaxItemId = initializeMaxItemId(db);
554 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700555
556 // When a new DB is created, remove all previously stored managed profile information.
557 ManagedProfileHeuristic.processAllUsers(Collections.EMPTY_LIST, mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800558 }
559
Adam Cohendcd297f2013-06-18 13:13:40 -0700560 private void addWorkspacesTable(SQLiteDatabase db) {
561 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800562 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400563 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
564 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700565 ");");
566 }
567
Adam Cohen119285e2014-04-02 16:59:08 -0700568 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700569 // Delete items directly on the workspace who's screen id doesn't exist
570 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
571 // AND container = -100"
572 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
573 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700574 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700575 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
576 " AND " +
577 LauncherSettings.Favorites.CONTAINER + " = " +
578 LauncherSettings.Favorites.CONTAINER_DESKTOP;
579 db.execSQL(removeOrphanedDesktopItems);
580
581 // Delete items contained in folders which no longer exist (after above statement)
582 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
583 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
584 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
585 " WHERE " +
586 LauncherSettings.Favorites.CONTAINER + " <> " +
587 LauncherSettings.Favorites.CONTAINER_DESKTOP +
588 " AND "
589 + LauncherSettings.Favorites.CONTAINER + " <> " +
590 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
591 " AND "
592 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
593 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
594 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
595 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
596 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700597 }
598
Winson Chungc763c4e2013-07-19 13:49:06 -0700599 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400600 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700601 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800602 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700603 }
604
Winson Chungc763c4e2013-07-19 13:49:06 -0700605 private void setFlagEmptyDbCreated() {
606 String spKey = LauncherAppState.getSharedPreferencesKey();
607 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800608 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700609 }
610
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 @Override
612 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700613 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800614 switch (oldVersion) {
615 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800616 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800617 case 12: {
618 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
619 // to persist workspace screens and their relative order.
620 mMaxScreenId = 0;
621 addWorkspacesTable(db);
622 }
623 case 13: {
624 db.beginTransaction();
625 try {
626 // Insert new column for holding widget provider name
627 db.execSQL("ALTER TABLE favorites " +
628 "ADD COLUMN appWidgetProvider TEXT;");
629 db.setTransactionSuccessful();
630 } catch (SQLException ex) {
631 Log.e(TAG, ex.getMessage(), ex);
632 // Old version remains, which means we wipe old data
633 break;
634 } finally {
635 db.endTransaction();
636 }
637 }
638 case 14: {
639 db.beginTransaction();
640 try {
641 // Insert new column for holding update timestamp
642 db.execSQL("ALTER TABLE favorites " +
643 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
644 db.execSQL("ALTER TABLE workspaceScreens " +
645 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
646 db.setTransactionSuccessful();
647 } catch (SQLException ex) {
648 Log.e(TAG, ex.getMessage(), ex);
649 // Old version remains, which means we wipe old data
650 break;
651 } finally {
652 db.endTransaction();
653 }
654 }
655 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700656 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800657 // Old version remains, which means we wipe old data
658 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 }
660 }
661 case 16: {
662 // We use the db version upgrade here to identify users who may not have seen
663 // clings yet (because they weren't available), but for whom the clings are now
664 // available (tablet users). Because one of the possible cling flows (migration)
665 // is very destructive (wipes out workspaces), we want to prevent this from showing
666 // until clear data. We do so by marking that the clings have been shown.
667 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
668 }
669 case 17: {
670 // No-op
671 }
672 case 18: {
673 // Due to a data loss bug, some users may have items associated with screen ids
674 // which no longer exist. Since this can cause other problems, and since the user
675 // will never see these items anyway, we use database upgrade as an opportunity to
676 // clean things up.
677 removeOrphanedItems(db);
678 }
679 case 19: {
680 // Add userId column
681 if (!addProfileColumn(db)) {
682 // Old version remains, which means we wipe old data
683 break;
684 }
685 }
686 case 20:
687 if (!updateFolderItemsRank(db, true)) {
688 break;
689 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800690 case 21:
691 // Recreate workspace table with screen id a primary key
692 if (!recreateWorkspaceTable(db)) {
693 break;
694 }
695 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700696 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
697 // Old version remains, which means we wipe old data
698 break;
699 }
700 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700701 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700702 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700703 case 24:
704 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700705 case 25:
706 convertShortcutsToLauncherActivities(db);
707 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800708 // DB Upgraded successfully
709 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400710 }
711 }
712
Sunny Goyala2cc6242015-01-14 14:23:02 -0800713 // DB was not upgraded
714 Log.w(TAG, "Destroying all old data.");
715 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800717
Adam Cohen9b1d0622014-05-21 19:01:57 -0700718 @Override
719 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
720 // This shouldn't happen -- throw our hands up in the air and start over.
721 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
722 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700723 createEmptyDB(db);
724 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700725
Sunny Goyal42de82f2014-09-26 22:09:29 -0700726 /**
727 * Clears all the data for a fresh start.
728 */
729 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700730 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
731 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
732 onCreate(db);
733 }
734
Sunny Goyald2f38192015-02-25 10:46:34 -0800735 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700736 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
737 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
738 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700739 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700740 db.beginTransaction();
741 Cursor c = null;
742 SQLiteStatement updateStmt = null;
743
744 try {
745 // Only consider the primary user as other users can't have a shortcut.
746 long userSerial = UserManagerCompat.getInstance(mContext)
747 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
748 c = db.query(TABLE_FAVORITES, new String[] {
749 Favorites._ID,
750 Favorites.INTENT,
751 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
752 null, null, null, null);
753
754 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
755 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
756
757 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
758 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
759
760 while (c.moveToNext()) {
761 String intentDescription = c.getString(intentIndex);
762 Intent intent;
763 try {
764 intent = Intent.parseUri(intentDescription, 0);
765 } catch (URISyntaxException e) {
766 Log.e(TAG, "Unable to parse intent", e);
767 continue;
768 }
769
770 if (!InstallShortcutReceiver.isLauncherActivity(intent, mContext)) {
771 continue;
772 }
773
774 long id = c.getLong(idIndex);
775 updateStmt.bindLong(1, id);
776 updateStmt.execute();
777 }
778 db.setTransactionSuccessful();
779 } catch (SQLException ex) {
780 Log.w(TAG, "Error deduping shortcuts", ex);
781 } finally {
782 db.endTransaction();
783 if (c != null) {
784 c.close();
785 }
786 if (updateStmt != null) {
787 updateStmt.close();
788 }
789 }
790 }
791
792 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800793 * Recreates workspace table and migrates data to the new table.
794 */
795 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
796 db.beginTransaction();
797 try {
798 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
799 new String[] {LauncherSettings.WorkspaceScreens._ID},
800 null, null, null, null,
801 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
802 ArrayList<Long> sortedIDs = new ArrayList<Long>();
803 long maxId = 0;
804 try {
805 while (c.moveToNext()) {
806 Long id = c.getLong(0);
807 if (!sortedIDs.contains(id)) {
808 sortedIDs.add(id);
809 maxId = Math.max(maxId, id);
810 }
811 }
812 } finally {
813 c.close();
814 }
815
816 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
817 addWorkspacesTable(db);
818
819 // Add all screen ids back
820 int total = sortedIDs.size();
821 for (int i = 0; i < total; i++) {
822 ContentValues values = new ContentValues();
823 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
824 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
825 addModifiedTime(values);
826 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
827 }
828 db.setTransactionSuccessful();
829 mMaxScreenId = maxId;
830 } catch (SQLException ex) {
831 // Old version remains, which means we wipe old data
832 Log.e(TAG, ex.getMessage(), ex);
833 return false;
834 } finally {
835 db.endTransaction();
836 }
837 return true;
838 }
839
Adam Cohen091440a2015-03-18 14:16:05 -0700840 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800841 db.beginTransaction();
842 try {
843 if (addRankColumn) {
844 // Insert new column for holding rank
845 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
846 }
847
848 // Get a map for folder ID to folder width
849 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
850 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
851 + " GROUP BY container;",
852 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
853
854 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800855 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
856 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800857 new Object[] {c.getLong(1) + 1, c.getLong(0)});
858 }
859
860 c.close();
861 db.setTransactionSuccessful();
862 } catch (SQLException ex) {
863 // Old version remains, which means we wipe old data
864 Log.e(TAG, ex.getMessage(), ex);
865 return false;
866 } finally {
867 db.endTransaction();
868 }
869 return true;
870 }
871
Kenny Guyed131872014-04-30 03:02:21 +0100872 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700873 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
874 // Default to the serial number of this user, for older
875 // shortcuts.
876 long userSerialNumber = userManager.getSerialNumberForUser(
877 UserHandleCompat.myUserHandle());
878 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
879 }
880
881 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100882 db.beginTransaction();
883 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700884 db.execSQL("ALTER TABLE favorites ADD COLUMN "
885 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100886 db.setTransactionSuccessful();
887 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100888 Log.e(TAG, ex.getMessage(), ex);
889 return false;
890 } finally {
891 db.endTransaction();
892 }
893 return true;
894 }
895
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700896 // Generates a new ID to use for an object in your database. This method should be only
897 // called from the main UI thread. As an exception, we do call it when we call the
898 // constructor from the worker thread; however, this doesn't extend until after the
899 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
900 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700901 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700902 public long generateNewItemId() {
903 if (mMaxItemId < 0) {
904 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700905 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700906 mMaxItemId += 1;
907 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700908 }
909
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700910 @Override
911 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
912 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
913 }
914
Winson Chungc763c4e2013-07-19 13:49:06 -0700915 public void updateMaxItemId(long id) {
916 mMaxItemId = id + 1;
917 }
918
Chris Wren5dee7af2013-12-20 17:22:11 -0500919 public void checkId(String table, ContentValues values) {
920 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
921 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
922 mMaxScreenId = Math.max(id, mMaxScreenId);
923 } else {
924 mMaxItemId = Math.max(id, mMaxItemId);
925 }
926 }
927
Adam Cohendcd297f2013-06-18 13:13:40 -0700928 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800929 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700930 }
931
932 // Generates a new ID to use for an workspace screen in your database. This method
933 // should be only called from the main UI thread. As an exception, we do call it when we
934 // call the constructor from the worker thread; however, this doesn't extend until after the
935 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
936 // after that point
937 public long generateNewScreenId() {
938 if (mMaxScreenId < 0) {
939 throw new RuntimeException("Error: max screen id was not initialized");
940 }
941 mMaxScreenId += 1;
942 return mMaxScreenId;
943 }
944
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800946 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800947 }
948
Adam Cohen091440a2015-03-18 14:16:05 -0700949 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700950 // 1. Ensure that externally added items have a valid item id
951 long id = generateNewItemId();
952 values.put(LauncherSettings.Favorites._ID, id);
953
954 // 2. In the case of an app widget, and if no app widget id is specified, we
955 // attempt allocate and bind the widget.
956 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
957 if (itemType != null &&
958 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
959 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
960
961 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
962 ComponentName cn = ComponentName.unflattenFromString(
963 values.getAsString(Favorites.APPWIDGET_PROVIDER));
964
965 if (cn != null) {
966 try {
967 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700968 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700969 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700970 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700971 }
972 } catch (RuntimeException e) {
973 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700974 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700975 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700976 } else {
977 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700978 }
979 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700980
981 // Add screen id if not present
982 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
983 if (!addScreenIdIfNecessary(screenId)) {
984 return false;
985 }
Adam Cohena043fa82014-07-23 14:49:38 -0700986 return true;
987 }
988
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700989 // Returns true of screen id exists, or if successfully added
990 private boolean addScreenIdIfNecessary(long screenId) {
991 if (!hasScreenId(screenId)) {
992 int rank = getMaxScreenRank() + 1;
993
994 ContentValues v = new ContentValues();
995 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
996 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
997 if (dbInsertAndCheck(this, getWritableDatabase(),
998 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
999 return false;
1000 }
1001 }
1002 return true;
1003 }
1004
1005 private boolean hasScreenId(long screenId) {
1006 SQLiteDatabase db = getWritableDatabase();
1007 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1008 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1009 if (c != null) {
1010 int count = c.getCount();
1011 c.close();
1012 return count > 0;
1013 } else {
1014 return false;
1015 }
1016 }
1017
1018 private int getMaxScreenRank() {
1019 SQLiteDatabase db = getWritableDatabase();
1020 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1021 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1022
1023 // get the result
1024 final int maxRankIndex = 0;
1025 int rank = -1;
1026 if (c != null && c.moveToNext()) {
1027 rank = c.getInt(maxRankIndex);
1028 }
1029 if (c != null) {
1030 c.close();
1031 }
1032
1033 return rank;
1034 }
1035
Adam Cohen091440a2015-03-18 14:16:05 -07001036 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001037 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001038 // TODO: Use multiple loaders with fall-back and transaction.
1039 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001040
1041 // Add the screens specified by the items above
1042 Collections.sort(screenIds);
1043 int rank = 0;
1044 ContentValues values = new ContentValues();
1045 for (Long id : screenIds) {
1046 values.clear();
1047 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1048 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1049 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1050 throw new RuntimeException("Failed initialize screen table"
1051 + "from default layout");
1052 }
1053 rank++;
1054 }
1055
1056 // Ensure that the max ids are initialized
1057 mMaxItemId = initializeMaxItemId(db);
1058 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001059
Adam Cohen71483f42014-05-15 14:04:01 -07001060 return count;
1061 }
1062
Adam Cohen091440a2015-03-18 14:16:05 -07001063 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001064 final ContentResolver resolver = mContext.getContentResolver();
1065 Cursor c = null;
1066 int count = 0;
1067 int curScreen = 0;
1068
1069 try {
1070 c = resolver.query(uri, null, null, null, "title ASC");
1071 } catch (Exception e) {
1072 // Ignore
1073 }
1074
Dan Sandlerd5024042014-01-09 15:01:33 -05001075 // We already have a favorites database in the old provider
1076 if (c != null) {
1077 try {
1078 if (c.getCount() > 0) {
1079 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1080 final int intentIndex
1081 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1082 final int titleIndex
1083 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1084 final int iconTypeIndex
1085 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1086 final int iconIndex
1087 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1088 final int iconPackageIndex
1089 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1090 final int iconResourceIndex
1091 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1092 final int containerIndex
1093 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1094 final int itemTypeIndex
1095 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1096 final int screenIndex
1097 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1098 final int cellXIndex
1099 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1100 final int cellYIndex
1101 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1102 final int uriIndex
1103 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1104 final int displayModeIndex
1105 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001106 final int profileIndex
1107 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001108
1109 int i = 0;
1110 int curX = 0;
1111 int curY = 0;
1112
1113 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001114 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1115 final int width = (int) profile.numColumns;
1116 final int height = (int) profile.numRows;
1117 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001118
1119 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1120
Adam Cohen72960972014-01-15 18:13:55 -08001121 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1122 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001123 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001124
1125 while (c.moveToNext()) {
1126 final int itemType = c.getInt(itemTypeIndex);
1127 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1128 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1129 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1130 continue;
1131 }
1132
1133 final int cellX = c.getInt(cellXIndex);
1134 final int cellY = c.getInt(cellYIndex);
1135 final int screen = c.getInt(screenIndex);
1136 int container = c.getInt(containerIndex);
1137 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001138
1139 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1140 UserHandleCompat userHandle;
1141 final long userSerialNumber;
1142 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1143 userSerialNumber = c.getInt(profileIndex);
1144 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1145 } else {
1146 // Default to the serial number of this user, for older
1147 // shortcuts.
1148 userHandle = UserHandleCompat.myUserHandle();
1149 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1150 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001151
1152 if (userHandle == null) {
1153 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1154 continue;
1155 }
1156
Dan Sandlerd5024042014-01-09 15:01:33 -05001157 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001158 + c.getString(titleIndex) + "\" ("
1159 + cellX + "," + cellY + "@"
1160 + LauncherSettings.Favorites.containerToString(container)
1161 + "/" + screen
1162 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001163
1164 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001165
1166 final Intent intent;
1167 final ComponentName cn;
1168 try {
1169 intent = Intent.parseUri(intentStr, 0);
1170 } catch (URISyntaxException e) {
1171 // bogus intent?
1172 Launcher.addDumpLog(TAG,
1173 "skipping invalid intent uri", true);
1174 continue;
1175 }
1176
1177 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001178 if (TextUtils.isEmpty(intentStr)) {
1179 // no intent? no icon
1180 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1181 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001182 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001183 !LauncherModel.isValidPackageActivity(mContext, cn,
1184 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001185 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001186 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001187 "no longer exists.", true);
1188 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001189 } else if (container ==
1190 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1191 // Dedupe icons directly on the workspace
1192
Adam Cohen556f6132014-01-15 15:18:08 -08001193 // Canonicalize
1194 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001195 // does not, so we clear that out to keep them the same.
1196 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001197 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001198 int flags = intent.getFlags();
1199 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001200 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001201 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001202 if (seenIntents.contains(key)) {
1203 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001204 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001205 } else {
1206 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001207 }
1208 }
1209 }
1210
1211 ContentValues values = new ContentValues(c.getColumnCount());
1212 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1213 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1214 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1215 values.put(LauncherSettings.Favorites.ICON_TYPE,
1216 c.getInt(iconTypeIndex));
1217 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1218 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1219 c.getString(iconPackageIndex));
1220 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1221 c.getString(iconResourceIndex));
1222 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1223 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1224 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1225 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1226 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001227 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001228
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001229 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1230 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001231 }
1232
1233 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1234 // In a folder or in the hotseat, preserve position
1235 values.put(LauncherSettings.Favorites.SCREEN, screen);
1236 values.put(LauncherSettings.Favorites.CELLX, cellX);
1237 values.put(LauncherSettings.Favorites.CELLY, cellY);
1238 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001239 // For items contained directly on one of the workspace screen,
1240 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001241 }
1242
1243 values.put(LauncherSettings.Favorites.CONTAINER, container);
1244
Adam Cohen72960972014-01-15 18:13:55 -08001245 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1246 shortcuts.add(values);
1247 } else {
1248 folders.add(values);
1249 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001250 }
1251
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001252 // Now that we have all the hotseat icons, let's go through them left-right
1253 // and assign valid locations for them in the new hotseat
1254 final int N = hotseat.size();
1255 for (int idx=0; idx<N; idx++) {
1256 int hotseatX = hotseat.keyAt(idx);
1257 ContentValues values = hotseat.valueAt(idx);
1258
Adam Cohen2e6da152015-05-06 11:42:25 -07001259 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001260 // let's drop this in the next available hole in the hotseat
1261 while (++hotseatX < hotseatWidth) {
1262 if (hotseat.get(hotseatX) == null) {
1263 // found a spot! move it here
1264 values.put(LauncherSettings.Favorites.SCREEN,
1265 hotseatX);
1266 break;
1267 }
1268 }
1269 }
1270 if (hotseatX >= hotseatWidth) {
1271 // no room for you in the hotseat? it's off to the desktop with you
1272 values.put(LauncherSettings.Favorites.CONTAINER,
1273 Favorites.CONTAINER_DESKTOP);
1274 }
1275 }
1276
Adam Cohen72960972014-01-15 18:13:55 -08001277 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1278 // Folders first
1279 allItems.addAll(folders);
1280 // Then shortcuts
1281 allItems.addAll(shortcuts);
1282
1283 // Layout all the folders
1284 for (ContentValues values: allItems) {
1285 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1286 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1287 // Hotseat items and folder items have already had their
1288 // location information set. Nothing to be done here.
1289 continue;
1290 }
1291 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1292 values.put(LauncherSettings.Favorites.CELLX, curX);
1293 values.put(LauncherSettings.Favorites.CELLY, curY);
1294 curX = (curX + 1) % width;
1295 if (curX == 0) {
1296 curY = (curY + 1);
1297 }
1298 // Leave the last row of icons blank on every screen
1299 if (curY == height - 1) {
1300 curScreen = (int) generateNewScreenId();
1301 curY = 0;
1302 }
1303 }
1304
1305 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001306 db.beginTransaction();
1307 try {
Adam Cohen72960972014-01-15 18:13:55 -08001308 for (ContentValues row: allItems) {
1309 if (row == null) continue;
1310 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001311 < 0) {
1312 return;
1313 } else {
1314 count++;
1315 }
1316 }
1317 db.setTransactionSuccessful();
1318 } finally {
1319 db.endTransaction();
1320 }
1321 }
1322
1323 db.beginTransaction();
1324 try {
1325 for (i=0; i<=curScreen; i++) {
1326 final ContentValues values = new ContentValues();
1327 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1328 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1329 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1330 < 0) {
1331 return;
1332 }
1333 }
1334 db.setTransactionSuccessful();
1335 } finally {
1336 db.endTransaction();
1337 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001338
1339 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001340 }
1341 } finally {
1342 c.close();
1343 }
1344 }
1345
1346 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1347 + (curScreen+1) + " screens", true);
1348
1349 // ensure that new screens are created to hold these icons
1350 setFlagJustLoadedOldDb();
1351
1352 // Update max IDs; very important since we just grabbed IDs from another database
1353 mMaxItemId = initializeMaxItemId(db);
1354 mMaxScreenId = initializeMaxScreenId(db);
1355 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1356 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001357 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001358
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001359 /**
1360 * @return the max _id in the provided table.
1361 */
Adam Cohen091440a2015-03-18 14:16:05 -07001362 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001363 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1364 // get the result
1365 long id = -1;
1366 if (c != null && c.moveToNext()) {
1367 id = c.getLong(0);
1368 }
1369 if (c != null) {
1370 c.close();
1371 }
1372
1373 if (id == -1) {
1374 throw new RuntimeException("Error: could not query max id in " + table);
1375 }
1376
1377 return id;
1378 }
1379
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001380 static class SqlArguments {
1381 public final String table;
1382 public final String where;
1383 public final String[] args;
1384
1385 SqlArguments(Uri url, String where, String[] args) {
1386 if (url.getPathSegments().size() == 1) {
1387 this.table = url.getPathSegments().get(0);
1388 this.where = where;
1389 this.args = args;
1390 } else if (url.getPathSegments().size() != 2) {
1391 throw new IllegalArgumentException("Invalid URI: " + url);
1392 } else if (!TextUtils.isEmpty(where)) {
1393 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1394 } else {
1395 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001396 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001397 this.args = null;
1398 }
1399 }
1400
1401 SqlArguments(Uri url) {
1402 if (url.getPathSegments().size() == 1) {
1403 table = url.getPathSegments().get(0);
1404 where = null;
1405 args = null;
1406 } else {
1407 throw new IllegalArgumentException("Invalid URI: " + url);
1408 }
1409 }
1410 }
Adam Cohen72960972014-01-15 18:13:55 -08001411}