blob: ebe56011d428061202ecf71a55560f57bdfbe85c [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
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.net.Uri;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080039import android.os.StrictMode;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050042import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070043
Sunny Goyal0fe505b2014-08-06 09:55:36 -070044import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
45import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010046import com.android.launcher3.compat.UserHandleCompat;
47import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040048import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070049
Dan Sandlerd5024042014-01-09 15:01:33 -050050import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070051import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070053import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050054import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080057 private static final String TAG = "Launcher.LauncherProvider";
58 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
Sunny Goyal08f72612015-01-05 13:41:43 -080060 private static final int DATABASE_VERSION = 21;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061
Adam Cohene25af792013-06-06 23:08:25 -070062 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040063 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070066 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080068 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Adam Cohena043fa82014-07-23 14:49:38 -070070 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
71
Anjali Koppal67e7cae2014-03-13 12:14:12 -070072 private LauncherProviderChangeListener mListener;
73
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070074 /**
Romain Guy73b979d2009-06-09 12:57:21 -070075 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070076 * {@link AppWidgetHost#deleteHost()} is called during database creation.
77 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
78 */
79 static final Uri CONTENT_APPWIDGET_RESET_URI =
80 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070081
Michael Jurkaa8c760d2011-04-28 14:59:33 -070082 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080087 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080089 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 return true;
92 }
93
Winson Chung0b560dd2014-01-21 13:00:26 -080094 public boolean wasNewDbCreated() {
95 return mOpenHelper.wasNewDbCreated();
96 }
97
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
99 mListener = listener;
100 }
101
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102 @Override
103 public String getType(Uri uri) {
104 SqlArguments args = new SqlArguments(uri, null, null);
105 if (TextUtils.isEmpty(args.where)) {
106 return "vnd.android.cursor.dir/" + args.table;
107 } else {
108 return "vnd.android.cursor.item/" + args.table;
109 }
110 }
111
112 @Override
113 public Cursor query(Uri uri, String[] projection, String selection,
114 String[] selectionArgs, String sortOrder) {
115
116 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
117 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
118 qb.setTables(args.table);
119
Romain Guy73b979d2009-06-09 12:57:21 -0700120 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
122 result.setNotificationUri(getContext().getContentResolver(), uri);
123
124 return result;
125 }
126
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700127 private static long dbInsertAndCheck(DatabaseHelper helper,
128 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500129 if (values == null) {
130 throw new RuntimeException("Error: attempting to insert null values");
131 }
Adam Cohen71483f42014-05-15 14:04:01 -0700132 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 throw new RuntimeException("Error: attempting to add item without specifying an id");
134 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500135 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700136 return db.insert(table, nullColumnHack, values);
137 }
138
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139 @Override
140 public Uri insert(Uri uri, ContentValues initialValues) {
141 SqlArguments args = new SqlArguments(uri);
142
Adam Cohena043fa82014-07-23 14:49:38 -0700143 // In very limited cases, we support system|signature permission apps to add to the db
144 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
145 if (externalAdd != null && "true".equals(externalAdd)) {
146 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
147 return null;
148 }
149 }
150
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800151 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400152 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800154 if (rowId <= 0) return null;
155
156 uri = ContentUris.withAppendedId(uri, rowId);
157 sendNotify(uri);
158
159 return uri;
160 }
161
Adam Cohena043fa82014-07-23 14:49:38 -0700162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public int bulkInsert(Uri uri, ContentValues[] values) {
165 SqlArguments args = new SqlArguments(uri);
166
167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
168 db.beginTransaction();
169 try {
170 int numValues = values.length;
171 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400172 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
174 return 0;
175 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176 }
177 db.setTransactionSuccessful();
178 } finally {
179 db.endTransaction();
180 }
181
182 sendNotify(uri);
183 return values.length;
184 }
185
186 @Override
Yura085c8532014-02-11 15:15:29 +0000187 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
188 throws OperationApplicationException {
189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
190 db.beginTransaction();
191 try {
192 ContentProviderResult[] result = super.applyBatch(operations);
193 db.setTransactionSuccessful();
194 return result;
195 } finally {
196 db.endTransaction();
197 }
198 }
199
200 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 public int delete(Uri uri, String selection, String[] selectionArgs) {
202 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
203
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 int count = db.delete(args.table, args.where, args.args);
206 if (count > 0) sendNotify(uri);
207
208 return count;
209 }
210
211 @Override
212 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
213 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
214
Chris Wren1ada10d2013-09-13 18:01:38 -0400215 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
217 int count = db.update(args.table, values, args.where, args.args);
218 if (count > 0) sendNotify(uri);
219
220 return count;
221 }
222
223 private void sendNotify(Uri uri) {
224 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
225 if (notify == null || "true".equals(notify)) {
226 getContext().getContentResolver().notifyChange(uri, null);
227 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400228
229 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400230 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700231 if (mListener != null) {
232 mListener.onLauncherProviderChange();
233 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400234 }
235
236 private void addModifiedTime(ContentValues values) {
237 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 }
239
Adam Cohendcd297f2013-06-18 13:13:40 -0700240 public long generateNewItemId() {
241 return mOpenHelper.generateNewItemId();
242 }
243
Winson Chungc763c4e2013-07-19 13:49:06 -0700244 public void updateMaxItemId(long id) {
245 mOpenHelper.updateMaxItemId(id);
246 }
247
Adam Cohendcd297f2013-06-18 13:13:40 -0700248 public long generateNewScreenId() {
249 return mOpenHelper.generateNewScreenId();
250 }
251
Brian Muramatsu5524b492012-10-02 16:55:54 -0700252 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700253 * Clears all the data for a fresh start.
254 */
255 synchronized public void createEmptyDB() {
256 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
257 }
258
Sunny Goyal33d44382014-10-16 09:24:19 -0700259 public void clearFlagEmptyDbCreated() {
260 String spKey = LauncherAppState.getSharedPreferencesKey();
261 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
262 .edit()
263 .remove(EMPTY_DATABASE_CREATED)
264 .commit();
265 }
266
Sunny Goyal42de82f2014-09-26 22:09:29 -0700267 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700268 * Loads the default workspace based on the following priority scheme:
269 * 1) From a package provided by play store
270 * 2) From a partner configuration APK, already in the system image
271 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700272 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700273 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400274 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700275 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700276
Winson Chungc763c4e2013-07-19 13:49:06 -0700277 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500278 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200279
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700280 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700281 mOpenHelper.mAppWidgetHost, mOpenHelper);
282
283 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700284 final Partner partner = Partner.get(getContext().getPackageManager());
285 if (partner != null && partner.hasDefaultLayout()) {
286 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700287 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700288 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700289 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700290 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
291 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700292 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700293 }
294 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700295
Sunny Goyal9d219682014-10-23 14:21:02 -0700296 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700297 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700298 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700299 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700300 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700301 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
302 && usingExternallyProvidedLayout) {
303 // Unable to load external layout. Cleanup and load the internal layout.
304 createEmptyDB();
305 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
306 getDefaultLayoutParser());
307 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700308 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700309 }
310 }
311
Sunny Goyal9d219682014-10-23 14:21:02 -0700312 private DefaultLayoutParser getDefaultLayoutParser() {
313 int defaultLayout = LauncherAppState.getInstance()
314 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
315 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
316 mOpenHelper, getContext().getResources(), defaultLayout);
317 }
318
Dan Sandlerd5024042014-01-09 15:01:33 -0500319 public void migrateLauncher2Shortcuts() {
320 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400321 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500322 }
323
Sunny Goyal08f72612015-01-05 13:41:43 -0800324 public void updateFolderItemsRank() {
325 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
326 }
327
Dan Sandlerd5024042014-01-09 15:01:33 -0500328 public void deleteDatabase() {
329 // Are you sure? (y/n)
330 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500331 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500332 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500333 if (dbFile.exists()) {
334 SQLiteDatabase.deleteDatabase(dbFile);
335 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 mOpenHelper = new DatabaseHelper(getContext());
337 }
338
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700339 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700341 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700342 private long mMaxItemId = -1;
343 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344
Winson Chung0b560dd2014-01-21 13:00:26 -0800345 private boolean mNewDbCreated = false;
346
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100348 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700350 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700351
352 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
353 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700354 if (mMaxItemId == -1) {
355 mMaxItemId = initializeMaxItemId(getWritableDatabase());
356 }
357 if (mMaxScreenId == -1) {
358 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700359 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 }
361
Winson Chung0b560dd2014-01-21 13:00:26 -0800362 public boolean wasNewDbCreated() {
363 return mNewDbCreated;
364 }
365
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700366 /**
367 * Send notification that we've deleted the {@link AppWidgetHost},
368 * probably as part of the initial database creation. The receiver may
369 * want to re-call {@link AppWidgetHost#startListening()} to ensure
370 * callbacks are correctly set.
371 */
372 private void sendAppWidgetResetNotify() {
373 final ContentResolver resolver = mContext.getContentResolver();
374 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
375 }
376
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800377 @Override
378 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800379 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700380
Adam Cohendcd297f2013-06-18 13:13:40 -0700381 mMaxItemId = 1;
382 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800383 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700384
Kenny Guyed131872014-04-30 03:02:21 +0100385 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
386 long userSerialNumber = userManager.getSerialNumberForUser(
387 UserHandleCompat.myUserHandle());
388
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 db.execSQL("CREATE TABLE favorites (" +
390 "_id INTEGER PRIMARY KEY," +
391 "title TEXT," +
392 "intent TEXT," +
393 "container INTEGER," +
394 "screen INTEGER," +
395 "cellX INTEGER," +
396 "cellY INTEGER," +
397 "spanX INTEGER," +
398 "spanY INTEGER," +
399 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700400 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800401 "isShortcut INTEGER," +
402 "iconType INTEGER," +
403 "iconPackage TEXT," +
404 "iconResource TEXT," +
405 "icon BLOB," +
406 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400407 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400408 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500409 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100410 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800411 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
412 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800413 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700414 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800415
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700416 // Database was just created, so wipe any previous widgets
417 if (mAppWidgetHost != null) {
418 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700419 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800420 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700421
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800422 // Fresh and clean launcher DB.
423 mMaxItemId = initializeMaxItemId(db);
424 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 }
426
Adam Cohendcd297f2013-06-18 13:13:40 -0700427 private void addWorkspacesTable(SQLiteDatabase db) {
428 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
429 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400430 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
431 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 ");");
433 }
434
Adam Cohen119285e2014-04-02 16:59:08 -0700435 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700436 // Delete items directly on the workspace who's screen id doesn't exist
437 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
438 // AND container = -100"
439 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
440 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700441 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700442 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
443 " AND " +
444 LauncherSettings.Favorites.CONTAINER + " = " +
445 LauncherSettings.Favorites.CONTAINER_DESKTOP;
446 db.execSQL(removeOrphanedDesktopItems);
447
448 // Delete items contained in folders which no longer exist (after above statement)
449 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
450 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
451 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
452 " WHERE " +
453 LauncherSettings.Favorites.CONTAINER + " <> " +
454 LauncherSettings.Favorites.CONTAINER_DESKTOP +
455 " AND "
456 + LauncherSettings.Favorites.CONTAINER + " <> " +
457 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
458 " AND "
459 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
460 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
461 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
462 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
463 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700464 }
465
Winson Chungc763c4e2013-07-19 13:49:06 -0700466 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400467 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700468 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800469 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700470 }
471
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 private void setFlagEmptyDbCreated() {
473 String spKey = LauncherAppState.getSharedPreferencesKey();
474 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800475 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700476 }
477
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800478 @Override
479 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700480 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800481 switch (oldVersion) {
482 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800483 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800484 case 12: {
485 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
486 // to persist workspace screens and their relative order.
487 mMaxScreenId = 0;
488 addWorkspacesTable(db);
489 }
490 case 13: {
491 db.beginTransaction();
492 try {
493 // Insert new column for holding widget provider name
494 db.execSQL("ALTER TABLE favorites " +
495 "ADD COLUMN appWidgetProvider TEXT;");
496 db.setTransactionSuccessful();
497 } catch (SQLException ex) {
498 Log.e(TAG, ex.getMessage(), ex);
499 // Old version remains, which means we wipe old data
500 break;
501 } finally {
502 db.endTransaction();
503 }
504 }
505 case 14: {
506 db.beginTransaction();
507 try {
508 // Insert new column for holding update timestamp
509 db.execSQL("ALTER TABLE favorites " +
510 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
511 db.execSQL("ALTER TABLE workspaceScreens " +
512 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
513 db.setTransactionSuccessful();
514 } catch (SQLException ex) {
515 Log.e(TAG, ex.getMessage(), ex);
516 // Old version remains, which means we wipe old data
517 break;
518 } finally {
519 db.endTransaction();
520 }
521 }
522 case 15: {
523 db.beginTransaction();
524 try {
525 // Insert new column for holding restore status
526 db.execSQL("ALTER TABLE favorites " +
527 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
528 db.setTransactionSuccessful();
529 } catch (SQLException ex) {
530 Log.e(TAG, ex.getMessage(), ex);
531 // Old version remains, which means we wipe old data
532 break;
533 } finally {
534 db.endTransaction();
535 }
536 }
537 case 16: {
538 // We use the db version upgrade here to identify users who may not have seen
539 // clings yet (because they weren't available), but for whom the clings are now
540 // available (tablet users). Because one of the possible cling flows (migration)
541 // is very destructive (wipes out workspaces), we want to prevent this from showing
542 // until clear data. We do so by marking that the clings have been shown.
543 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
544 }
545 case 17: {
546 // No-op
547 }
548 case 18: {
549 // Due to a data loss bug, some users may have items associated with screen ids
550 // which no longer exist. Since this can cause other problems, and since the user
551 // will never see these items anyway, we use database upgrade as an opportunity to
552 // clean things up.
553 removeOrphanedItems(db);
554 }
555 case 19: {
556 // Add userId column
557 if (!addProfileColumn(db)) {
558 // Old version remains, which means we wipe old data
559 break;
560 }
561 }
562 case 20:
563 if (!updateFolderItemsRank(db, true)) {
564 break;
565 }
566 case 21: {
567 // DB Upgraded successfully
568 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400569 }
570 }
571
Sunny Goyala2cc6242015-01-14 14:23:02 -0800572 // DB was not upgraded
573 Log.w(TAG, "Destroying all old data.");
574 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800576
Adam Cohen9b1d0622014-05-21 19:01:57 -0700577 @Override
578 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
579 // This shouldn't happen -- throw our hands up in the air and start over.
580 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
581 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700582 createEmptyDB(db);
583 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700584
Sunny Goyal42de82f2014-09-26 22:09:29 -0700585
586 /**
587 * Clears all the data for a fresh start.
588 */
589 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700590 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
591 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
592 onCreate(db);
593 }
594
Sunny Goyal08f72612015-01-05 13:41:43 -0800595 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
596 db.beginTransaction();
597 try {
598 if (addRankColumn) {
599 // Insert new column for holding rank
600 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
601 }
602
603 // Get a map for folder ID to folder width
604 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
605 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
606 + " GROUP BY container;",
607 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
608
609 while (c.moveToNext()) {
610 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE container=?;",
611 new Object[] {c.getLong(1) + 1, c.getLong(0)});
612 }
613
614 c.close();
615 db.setTransactionSuccessful();
616 } catch (SQLException ex) {
617 // Old version remains, which means we wipe old data
618 Log.e(TAG, ex.getMessage(), ex);
619 return false;
620 } finally {
621 db.endTransaction();
622 }
623 return true;
624 }
625
Kenny Guyed131872014-04-30 03:02:21 +0100626 private boolean addProfileColumn(SQLiteDatabase db) {
627 db.beginTransaction();
628 try {
629 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
630 // Default to the serial number of this user, for older
631 // shortcuts.
632 long userSerialNumber = userManager.getSerialNumberForUser(
633 UserHandleCompat.myUserHandle());
634 // Insert new column for holding user serial number
635 db.execSQL("ALTER TABLE favorites " +
636 "ADD COLUMN profileId INTEGER DEFAULT "
637 + userSerialNumber + ";");
638 db.setTransactionSuccessful();
639 } catch (SQLException ex) {
640 // Old version remains, which means we wipe old data
641 Log.e(TAG, ex.getMessage(), ex);
642 return false;
643 } finally {
644 db.endTransaction();
645 }
646 return true;
647 }
648
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700649 // Generates a new ID to use for an object in your database. This method should be only
650 // called from the main UI thread. As an exception, we do call it when we call the
651 // constructor from the worker thread; however, this doesn't extend until after the
652 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
653 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700654 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700655 public long generateNewItemId() {
656 if (mMaxItemId < 0) {
657 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700658 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700659 mMaxItemId += 1;
660 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700661 }
662
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700663 @Override
664 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
665 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
666 }
667
Winson Chungc763c4e2013-07-19 13:49:06 -0700668 public void updateMaxItemId(long id) {
669 mMaxItemId = id + 1;
670 }
671
Chris Wren5dee7af2013-12-20 17:22:11 -0500672 public void checkId(String table, ContentValues values) {
673 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
674 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
675 mMaxScreenId = Math.max(id, mMaxScreenId);
676 } else {
677 mMaxItemId = Math.max(id, mMaxItemId);
678 }
679 }
680
Adam Cohendcd297f2013-06-18 13:13:40 -0700681 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700682 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
683
684 // get the result
685 final int maxIdIndex = 0;
686 long id = -1;
687 if (c != null && c.moveToNext()) {
688 id = c.getLong(maxIdIndex);
689 }
Michael Jurka5130e402011-10-13 04:55:35 -0700690 if (c != null) {
691 c.close();
692 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700693
694 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700695 throw new RuntimeException("Error: could not query max item id");
696 }
697
698 return id;
699 }
700
701 // Generates a new ID to use for an workspace screen in your database. This method
702 // should be only called from the main UI thread. As an exception, we do call it when we
703 // call the constructor from the worker thread; however, this doesn't extend until after the
704 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
705 // after that point
706 public long generateNewScreenId() {
707 if (mMaxScreenId < 0) {
708 throw new RuntimeException("Error: max screen id was not initialized");
709 }
710 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800711 // Log to disk
712 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 return mMaxScreenId;
714 }
715
Adam Cohendcd297f2013-06-18 13:13:40 -0700716 private long initializeMaxScreenId(SQLiteDatabase db) {
717 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
718
719 // get the result
720 final int maxIdIndex = 0;
721 long id = -1;
722 if (c != null && c.moveToNext()) {
723 id = c.getLong(maxIdIndex);
724 }
725 if (c != null) {
726 c.close();
727 }
728
729 if (id == -1) {
730 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700731 }
732
Winson Chunga90303b2013-11-15 13:05:06 -0800733 // Log to disk
734 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700735 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800736 }
737
Adam Cohena043fa82014-07-23 14:49:38 -0700738 private boolean initializeExternalAdd(ContentValues values) {
739 // 1. Ensure that externally added items have a valid item id
740 long id = generateNewItemId();
741 values.put(LauncherSettings.Favorites._ID, id);
742
743 // 2. In the case of an app widget, and if no app widget id is specified, we
744 // attempt allocate and bind the widget.
745 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
746 if (itemType != null &&
747 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
748 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
749
750 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
751 ComponentName cn = ComponentName.unflattenFromString(
752 values.getAsString(Favorites.APPWIDGET_PROVIDER));
753
754 if (cn != null) {
755 try {
756 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700757 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700758 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700759 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700760 }
761 } catch (RuntimeException e) {
762 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700763 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700764 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700765 } else {
766 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700767 }
768 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700769
770 // Add screen id if not present
771 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
772 if (!addScreenIdIfNecessary(screenId)) {
773 return false;
774 }
Adam Cohena043fa82014-07-23 14:49:38 -0700775 return true;
776 }
777
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700778 // Returns true of screen id exists, or if successfully added
779 private boolean addScreenIdIfNecessary(long screenId) {
780 if (!hasScreenId(screenId)) {
781 int rank = getMaxScreenRank() + 1;
782
783 ContentValues v = new ContentValues();
784 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
785 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
786 if (dbInsertAndCheck(this, getWritableDatabase(),
787 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
788 return false;
789 }
790 }
791 return true;
792 }
793
794 private boolean hasScreenId(long screenId) {
795 SQLiteDatabase db = getWritableDatabase();
796 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
797 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
798 if (c != null) {
799 int count = c.getCount();
800 c.close();
801 return count > 0;
802 } else {
803 return false;
804 }
805 }
806
807 private int getMaxScreenRank() {
808 SQLiteDatabase db = getWritableDatabase();
809 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
810 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
811
812 // get the result
813 final int maxRankIndex = 0;
814 int rank = -1;
815 if (c != null && c.moveToNext()) {
816 rank = c.getInt(maxRankIndex);
817 }
818 if (c != null) {
819 c.close();
820 }
821
822 return rank;
823 }
824
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700825 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700826 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700827 // TODO: Use multiple loaders with fall-back and transaction.
828 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700829
830 // Add the screens specified by the items above
831 Collections.sort(screenIds);
832 int rank = 0;
833 ContentValues values = new ContentValues();
834 for (Long id : screenIds) {
835 values.clear();
836 values.put(LauncherSettings.WorkspaceScreens._ID, id);
837 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
838 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
839 throw new RuntimeException("Failed initialize screen table"
840 + "from default layout");
841 }
842 rank++;
843 }
844
845 // Ensure that the max ids are initialized
846 mMaxItemId = initializeMaxItemId(db);
847 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700848
Adam Cohen71483f42014-05-15 14:04:01 -0700849 return count;
850 }
851
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700852 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500853 final ContentResolver resolver = mContext.getContentResolver();
854 Cursor c = null;
855 int count = 0;
856 int curScreen = 0;
857
858 try {
859 c = resolver.query(uri, null, null, null, "title ASC");
860 } catch (Exception e) {
861 // Ignore
862 }
863
Dan Sandlerd5024042014-01-09 15:01:33 -0500864 // We already have a favorites database in the old provider
865 if (c != null) {
866 try {
867 if (c.getCount() > 0) {
868 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
869 final int intentIndex
870 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
871 final int titleIndex
872 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
873 final int iconTypeIndex
874 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
875 final int iconIndex
876 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
877 final int iconPackageIndex
878 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
879 final int iconResourceIndex
880 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
881 final int containerIndex
882 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
883 final int itemTypeIndex
884 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
885 final int screenIndex
886 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
887 final int cellXIndex
888 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
889 final int cellYIndex
890 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
891 final int uriIndex
892 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
893 final int displayModeIndex
894 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100895 final int profileIndex
896 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500897
898 int i = 0;
899 int curX = 0;
900 int curY = 0;
901
902 final LauncherAppState app = LauncherAppState.getInstance();
903 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
904 final int width = (int) grid.numColumns;
905 final int height = (int) grid.numRows;
906 final int hotseatWidth = (int) grid.numHotseatIcons;
907
908 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
909
Adam Cohen72960972014-01-15 18:13:55 -0800910 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
911 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500912 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500913
914 while (c.moveToNext()) {
915 final int itemType = c.getInt(itemTypeIndex);
916 if (itemType != Favorites.ITEM_TYPE_APPLICATION
917 && itemType != Favorites.ITEM_TYPE_SHORTCUT
918 && itemType != Favorites.ITEM_TYPE_FOLDER) {
919 continue;
920 }
921
922 final int cellX = c.getInt(cellXIndex);
923 final int cellY = c.getInt(cellYIndex);
924 final int screen = c.getInt(screenIndex);
925 int container = c.getInt(containerIndex);
926 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100927
928 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
929 UserHandleCompat userHandle;
930 final long userSerialNumber;
931 if (profileIndex != -1 && !c.isNull(profileIndex)) {
932 userSerialNumber = c.getInt(profileIndex);
933 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
934 } else {
935 // Default to the serial number of this user, for older
936 // shortcuts.
937 userHandle = UserHandleCompat.myUserHandle();
938 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
939 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800940
941 if (userHandle == null) {
942 Launcher.addDumpLog(TAG, "skipping deleted user", true);
943 continue;
944 }
945
Dan Sandlerd5024042014-01-09 15:01:33 -0500946 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500947 + c.getString(titleIndex) + "\" ("
948 + cellX + "," + cellY + "@"
949 + LauncherSettings.Favorites.containerToString(container)
950 + "/" + screen
951 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500952
953 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800954
955 final Intent intent;
956 final ComponentName cn;
957 try {
958 intent = Intent.parseUri(intentStr, 0);
959 } catch (URISyntaxException e) {
960 // bogus intent?
961 Launcher.addDumpLog(TAG,
962 "skipping invalid intent uri", true);
963 continue;
964 }
965
966 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500967 if (TextUtils.isEmpty(intentStr)) {
968 // no intent? no icon
969 Launcher.addDumpLog(TAG, "skipping empty intent", true);
970 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800971 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100972 !LauncherModel.isValidPackageActivity(mContext, cn,
973 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800974 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800975 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -0800976 "no longer exists.", true);
977 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800978 } else if (container ==
979 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
980 // Dedupe icons directly on the workspace
981
Adam Cohen556f6132014-01-15 15:18:08 -0800982 // Canonicalize
983 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -0700984 // does not, so we clear that out to keep them the same.
985 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -0800986 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -0700987 int flags = intent.getFlags();
988 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -0800989 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -0700990 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -0800991 if (seenIntents.contains(key)) {
992 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500993 continue;
Adam Cohen556f6132014-01-15 15:18:08 -0800994 } else {
995 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -0500996 }
997 }
998 }
999
1000 ContentValues values = new ContentValues(c.getColumnCount());
1001 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1002 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1003 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1004 values.put(LauncherSettings.Favorites.ICON_TYPE,
1005 c.getInt(iconTypeIndex));
1006 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1007 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1008 c.getString(iconPackageIndex));
1009 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1010 c.getString(iconResourceIndex));
1011 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1012 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1013 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1014 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1015 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001016 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001017
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001018 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1019 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001020 }
1021
1022 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1023 // In a folder or in the hotseat, preserve position
1024 values.put(LauncherSettings.Favorites.SCREEN, screen);
1025 values.put(LauncherSettings.Favorites.CELLX, cellX);
1026 values.put(LauncherSettings.Favorites.CELLY, cellY);
1027 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001028 // For items contained directly on one of the workspace screen,
1029 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001030 }
1031
1032 values.put(LauncherSettings.Favorites.CONTAINER, container);
1033
Adam Cohen72960972014-01-15 18:13:55 -08001034 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1035 shortcuts.add(values);
1036 } else {
1037 folders.add(values);
1038 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001039 }
1040
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001041 // Now that we have all the hotseat icons, let's go through them left-right
1042 // and assign valid locations for them in the new hotseat
1043 final int N = hotseat.size();
1044 for (int idx=0; idx<N; idx++) {
1045 int hotseatX = hotseat.keyAt(idx);
1046 ContentValues values = hotseat.valueAt(idx);
1047
1048 if (hotseatX == grid.hotseatAllAppsRank) {
1049 // let's drop this in the next available hole in the hotseat
1050 while (++hotseatX < hotseatWidth) {
1051 if (hotseat.get(hotseatX) == null) {
1052 // found a spot! move it here
1053 values.put(LauncherSettings.Favorites.SCREEN,
1054 hotseatX);
1055 break;
1056 }
1057 }
1058 }
1059 if (hotseatX >= hotseatWidth) {
1060 // no room for you in the hotseat? it's off to the desktop with you
1061 values.put(LauncherSettings.Favorites.CONTAINER,
1062 Favorites.CONTAINER_DESKTOP);
1063 }
1064 }
1065
Adam Cohen72960972014-01-15 18:13:55 -08001066 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1067 // Folders first
1068 allItems.addAll(folders);
1069 // Then shortcuts
1070 allItems.addAll(shortcuts);
1071
1072 // Layout all the folders
1073 for (ContentValues values: allItems) {
1074 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1075 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1076 // Hotseat items and folder items have already had their
1077 // location information set. Nothing to be done here.
1078 continue;
1079 }
1080 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1081 values.put(LauncherSettings.Favorites.CELLX, curX);
1082 values.put(LauncherSettings.Favorites.CELLY, curY);
1083 curX = (curX + 1) % width;
1084 if (curX == 0) {
1085 curY = (curY + 1);
1086 }
1087 // Leave the last row of icons blank on every screen
1088 if (curY == height - 1) {
1089 curScreen = (int) generateNewScreenId();
1090 curY = 0;
1091 }
1092 }
1093
1094 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001095 db.beginTransaction();
1096 try {
Adam Cohen72960972014-01-15 18:13:55 -08001097 for (ContentValues row: allItems) {
1098 if (row == null) continue;
1099 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001100 < 0) {
1101 return;
1102 } else {
1103 count++;
1104 }
1105 }
1106 db.setTransactionSuccessful();
1107 } finally {
1108 db.endTransaction();
1109 }
1110 }
1111
1112 db.beginTransaction();
1113 try {
1114 for (i=0; i<=curScreen; i++) {
1115 final ContentValues values = new ContentValues();
1116 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1117 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1118 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1119 < 0) {
1120 return;
1121 }
1122 }
1123 db.setTransactionSuccessful();
1124 } finally {
1125 db.endTransaction();
1126 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001127
1128 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001129 }
1130 } finally {
1131 c.close();
1132 }
1133 }
1134
1135 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1136 + (curScreen+1) + " screens", true);
1137
1138 // ensure that new screens are created to hold these icons
1139 setFlagJustLoadedOldDb();
1140
1141 // Update max IDs; very important since we just grabbed IDs from another database
1142 mMaxItemId = initializeMaxItemId(db);
1143 mMaxScreenId = initializeMaxScreenId(db);
1144 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1145 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001146 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001147
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 static class SqlArguments {
1149 public final String table;
1150 public final String where;
1151 public final String[] args;
1152
1153 SqlArguments(Uri url, String where, String[] args) {
1154 if (url.getPathSegments().size() == 1) {
1155 this.table = url.getPathSegments().get(0);
1156 this.where = where;
1157 this.args = args;
1158 } else if (url.getPathSegments().size() != 2) {
1159 throw new IllegalArgumentException("Invalid URI: " + url);
1160 } else if (!TextUtils.isEmpty(where)) {
1161 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1162 } else {
1163 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001164 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001165 this.args = null;
1166 }
1167 }
1168
1169 SqlArguments(Uri url) {
1170 if (url.getPathSegments().size() == 1) {
1171 table = url.getPathSegments().get(0);
1172 where = null;
1173 args = null;
1174 } else {
1175 throw new IllegalArgumentException("Invalid URI: " + url);
1176 }
1177 }
1178 }
Adam Cohen72960972014-01-15 18:13:55 -08001179}