blob: 9233bcb0fa83bf712ec02d5efb667e83302286bb [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;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050041import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070042
Sunny Goyal0fe505b2014-08-06 09:55:36 -070043import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
44import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010045import com.android.launcher3.compat.UserHandleCompat;
46import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040047import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070048
Dan Sandlerd5024042014-01-09 15:01:33 -050049import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070050import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070051import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070052import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050053import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080054
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080056 private static final String TAG = "Launcher.LauncherProvider";
57 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080058
Sunny Goyale87e6ab2014-11-21 22:42:53 -080059 private static final int MIN_DATABASE_VERSION = 12;
Kenny Guyed131872014-04-30 03:02:21 +010060 private static final int DATABASE_VERSION = 20;
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 UPGRADED_FROM_OLD_DATABASE = "UPGRADED_FROM_OLD_DATABASE";
69 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Adam Cohena043fa82014-07-23 14:49:38 -070071 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
72
Anjali Koppal67e7cae2014-03-13 12:14:12 -070073 private LauncherProviderChangeListener mListener;
74
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070075 /**
Romain Guy73b979d2009-06-09 12:57:21 -070076 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070077 * {@link AppWidgetHost#deleteHost()} is called during database creation.
78 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
79 */
80 static final Uri CONTENT_APPWIDGET_RESET_URI =
81 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070082
Michael Jurkaa8c760d2011-04-28 14:59:33 -070083 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
85 @Override
86 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040087 final Context context = getContext();
88 mOpenHelper = new DatabaseHelper(context);
89 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090 return true;
91 }
92
Winson Chung0b560dd2014-01-21 13:00:26 -080093 public boolean wasNewDbCreated() {
94 return mOpenHelper.wasNewDbCreated();
95 }
96
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
98 mListener = listener;
99 }
100
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101 @Override
102 public String getType(Uri uri) {
103 SqlArguments args = new SqlArguments(uri, null, null);
104 if (TextUtils.isEmpty(args.where)) {
105 return "vnd.android.cursor.dir/" + args.table;
106 } else {
107 return "vnd.android.cursor.item/" + args.table;
108 }
109 }
110
111 @Override
112 public Cursor query(Uri uri, String[] projection, String selection,
113 String[] selectionArgs, String sortOrder) {
114
115 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
116 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
117 qb.setTables(args.table);
118
Romain Guy73b979d2009-06-09 12:57:21 -0700119 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
121 result.setNotificationUri(getContext().getContentResolver(), uri);
122
123 return result;
124 }
125
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700126 private static long dbInsertAndCheck(DatabaseHelper helper,
127 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500128 if (values == null) {
129 throw new RuntimeException("Error: attempting to insert null values");
130 }
Adam Cohen71483f42014-05-15 14:04:01 -0700131 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700132 throw new RuntimeException("Error: attempting to add item without specifying an id");
133 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500134 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 return db.insert(table, nullColumnHack, values);
136 }
137
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800138 @Override
139 public Uri insert(Uri uri, ContentValues initialValues) {
140 SqlArguments args = new SqlArguments(uri);
141
Adam Cohena043fa82014-07-23 14:49:38 -0700142 // In very limited cases, we support system|signature permission apps to add to the db
143 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
144 if (externalAdd != null && "true".equals(externalAdd)) {
145 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
146 return null;
147 }
148 }
149
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400151 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 if (rowId <= 0) return null;
154
155 uri = ContentUris.withAppendedId(uri, rowId);
156 sendNotify(uri);
157
158 return uri;
159 }
160
Adam Cohena043fa82014-07-23 14:49:38 -0700161
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800162 @Override
163 public int bulkInsert(Uri uri, ContentValues[] values) {
164 SqlArguments args = new SqlArguments(uri);
165
166 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
167 db.beginTransaction();
168 try {
169 int numValues = values.length;
170 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400171 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700172 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
173 return 0;
174 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175 }
176 db.setTransactionSuccessful();
177 } finally {
178 db.endTransaction();
179 }
180
181 sendNotify(uri);
182 return values.length;
183 }
184
185 @Override
Yura085c8532014-02-11 15:15:29 +0000186 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
187 throws OperationApplicationException {
188 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
189 db.beginTransaction();
190 try {
191 ContentProviderResult[] result = super.applyBatch(operations);
192 db.setTransactionSuccessful();
193 return result;
194 } finally {
195 db.endTransaction();
196 }
197 }
198
199 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 public int delete(Uri uri, String selection, String[] selectionArgs) {
201 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
202
203 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
204 int count = db.delete(args.table, args.where, args.args);
205 if (count > 0) sendNotify(uri);
206
207 return count;
208 }
209
210 @Override
211 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
212 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
213
Chris Wren1ada10d2013-09-13 18:01:38 -0400214 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
216 int count = db.update(args.table, values, args.where, args.args);
217 if (count > 0) sendNotify(uri);
218
219 return count;
220 }
221
222 private void sendNotify(Uri uri) {
223 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
224 if (notify == null || "true".equals(notify)) {
225 getContext().getContentResolver().notifyChange(uri, null);
226 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400227
228 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400229 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700230 if (mListener != null) {
231 mListener.onLauncherProviderChange();
232 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400233 }
234
235 private void addModifiedTime(ContentValues values) {
236 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237 }
238
Adam Cohendcd297f2013-06-18 13:13:40 -0700239 public long generateNewItemId() {
240 return mOpenHelper.generateNewItemId();
241 }
242
Winson Chungc763c4e2013-07-19 13:49:06 -0700243 public void updateMaxItemId(long id) {
244 mOpenHelper.updateMaxItemId(id);
245 }
246
Adam Cohendcd297f2013-06-18 13:13:40 -0700247 public long generateNewScreenId() {
248 return mOpenHelper.generateNewScreenId();
249 }
250
251 // This is only required one time while loading the workspace during the
252 // upgrade path, and should never be called from anywhere else.
253 public void updateMaxScreenId(long maxScreenId) {
254 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700255 }
256
Brian Muramatsu5524b492012-10-02 16:55:54 -0700257 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700258 * Clears all the data for a fresh start.
259 */
260 synchronized public void createEmptyDB() {
261 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
262 }
263
Sunny Goyal33d44382014-10-16 09:24:19 -0700264 public void clearFlagEmptyDbCreated() {
265 String spKey = LauncherAppState.getSharedPreferencesKey();
266 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
267 .edit()
268 .remove(EMPTY_DATABASE_CREATED)
269 .commit();
270 }
271
Sunny Goyal42de82f2014-09-26 22:09:29 -0700272 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700273 * Loads the default workspace based on the following priority scheme:
274 * 1) From a package provided by play store
275 * 2) From a partner configuration APK, already in the system image
276 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700277 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700278 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400279 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700280 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700281
Winson Chungc763c4e2013-07-19 13:49:06 -0700282 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500283 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200284
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700285 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700286 mOpenHelper.mAppWidgetHost, mOpenHelper);
287
288 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700289 final Partner partner = Partner.get(getContext().getPackageManager());
290 if (partner != null && partner.hasDefaultLayout()) {
291 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700292 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700293 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700294 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700295 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
296 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700297 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700298 }
299 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700300
Sunny Goyal9d219682014-10-23 14:21:02 -0700301 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700302 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700303 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700304 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700305 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700306 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
307 && usingExternallyProvidedLayout) {
308 // Unable to load external layout. Cleanup and load the internal layout.
309 createEmptyDB();
310 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
311 getDefaultLayoutParser());
312 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700313 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700314 }
315 }
316
Sunny Goyal9d219682014-10-23 14:21:02 -0700317 private DefaultLayoutParser getDefaultLayoutParser() {
318 int defaultLayout = LauncherAppState.getInstance()
319 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
320 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
321 mOpenHelper, getContext().getResources(), defaultLayout);
322 }
323
Dan Sandlerd5024042014-01-09 15:01:33 -0500324 public void migrateLauncher2Shortcuts() {
325 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400326 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500327 }
328
Dan Sandlerd5024042014-01-09 15:01:33 -0500329 public void deleteDatabase() {
330 // Are you sure? (y/n)
331 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500332 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500334 if (dbFile.exists()) {
335 SQLiteDatabase.deleteDatabase(dbFile);
336 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500337 mOpenHelper = new DatabaseHelper(getContext());
338 }
339
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700340 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700342 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700343 private long mMaxItemId = -1;
344 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345
Winson Chung0b560dd2014-01-21 13:00:26 -0800346 private boolean mNewDbCreated = false;
347
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100349 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700351 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700352
353 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
354 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700355 if (mMaxItemId == -1) {
356 mMaxItemId = initializeMaxItemId(getWritableDatabase());
357 }
358 if (mMaxScreenId == -1) {
359 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700360 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800361 }
362
Winson Chung0b560dd2014-01-21 13:00:26 -0800363 public boolean wasNewDbCreated() {
364 return mNewDbCreated;
365 }
366
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700367 /**
368 * Send notification that we've deleted the {@link AppWidgetHost},
369 * probably as part of the initial database creation. The receiver may
370 * want to re-call {@link AppWidgetHost#startListening()} to ensure
371 * callbacks are correctly set.
372 */
373 private void sendAppWidgetResetNotify() {
374 final ContentResolver resolver = mContext.getContentResolver();
375 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
376 }
377
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800378 @Override
379 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800380 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700381
Adam Cohendcd297f2013-06-18 13:13:40 -0700382 mMaxItemId = 1;
383 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800384 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700385
Kenny Guyed131872014-04-30 03:02:21 +0100386 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
387 long userSerialNumber = userManager.getSerialNumberForUser(
388 UserHandleCompat.myUserHandle());
389
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800390 db.execSQL("CREATE TABLE favorites (" +
391 "_id INTEGER PRIMARY KEY," +
392 "title TEXT," +
393 "intent TEXT," +
394 "container INTEGER," +
395 "screen INTEGER," +
396 "cellX INTEGER," +
397 "cellY INTEGER," +
398 "spanX INTEGER," +
399 "spanY INTEGER," +
400 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700401 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800402 "isShortcut INTEGER," +
403 "iconType INTEGER," +
404 "iconPackage TEXT," +
405 "iconResource TEXT," +
406 "icon BLOB," +
407 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400408 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400409 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500410 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100411 "restored INTEGER NOT NULL DEFAULT 0," +
412 "profileId INTEGER DEFAULT " + userSerialNumber +
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);
469 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700470 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
471 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700472 editor.commit();
473 }
474
Winson Chungc763c4e2013-07-19 13:49:06 -0700475 private void setFlagEmptyDbCreated() {
476 String spKey = LauncherAppState.getSharedPreferencesKey();
477 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
478 SharedPreferences.Editor editor = sp.edit();
479 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
480 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
481 editor.commit();
482 }
483
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 @Override
485 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700486 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700487
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800488 int version = oldVersion;
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800489 if (version < MIN_DATABASE_VERSION) {
490 // The version cannot be lower that this, as Launcher3 never supported a lower
491 // version of the DB.
492 createEmptyDB(db);
493 version = DATABASE_VERSION;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700494 }
495
Adam Cohendcd297f2013-06-18 13:13:40 -0700496 if (version < 13) {
497 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
498 // to persist workspace screens and their relative order.
499 mMaxScreenId = 0;
500
Adam Cohendcd297f2013-06-18 13:13:40 -0700501 addWorkspacesTable(db);
502 version = 13;
503 }
504
Chris Wrend5e66bf2013-09-16 14:02:29 -0400505 if (version < 14) {
506 db.beginTransaction();
507 try {
508 // Insert new column for holding widget provider name
509 db.execSQL("ALTER TABLE favorites " +
510 "ADD COLUMN appWidgetProvider TEXT;");
511 db.setTransactionSuccessful();
512 version = 14;
513 } catch (SQLException ex) {
514 // Old version remains, which means we wipe old data
515 Log.e(TAG, ex.getMessage(), ex);
516 } finally {
517 db.endTransaction();
518 }
519 }
520
Chris Wren1ada10d2013-09-13 18:01:38 -0400521 if (version < 15) {
522 db.beginTransaction();
523 try {
524 // Insert new column for holding update timestamp
525 db.execSQL("ALTER TABLE favorites " +
526 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
527 db.execSQL("ALTER TABLE workspaceScreens " +
528 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
529 db.setTransactionSuccessful();
530 version = 15;
531 } catch (SQLException ex) {
532 // Old version remains, which means we wipe old data
533 Log.e(TAG, ex.getMessage(), ex);
534 } finally {
535 db.endTransaction();
536 }
537 }
538
Chris Wrenf4d08112014-01-16 18:13:56 -0500539
540 if (version < 16) {
541 db.beginTransaction();
542 try {
543 // Insert new column for holding restore status
544 db.execSQL("ALTER TABLE favorites " +
545 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
546 db.setTransactionSuccessful();
547 version = 16;
548 } catch (SQLException ex) {
549 // Old version remains, which means we wipe old data
550 Log.e(TAG, ex.getMessage(), ex);
551 } finally {
552 db.endTransaction();
553 }
554 }
555
Adam Cohen71e03b92014-02-21 14:09:53 -0800556 if (version < 17) {
557 // We use the db version upgrade here to identify users who may not have seen
558 // clings yet (because they weren't available), but for whom the clings are now
559 // available (tablet users). Because one of the possible cling flows (migration)
560 // is very destructive (wipes out workspaces), we want to prevent this from showing
561 // until clear data. We do so by marking that the clings have been shown.
562 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
563 version = 17;
564 }
565
Adam Cohen119285e2014-04-02 16:59:08 -0700566 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700567 // No-op
568 version = 18;
569 }
570
571 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700572 // Due to a data loss bug, some users may have items associated with screen ids
573 // which no longer exist. Since this can cause other problems, and since the user
574 // will never see these items anyway, we use database upgrade as an opportunity to
575 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700576 removeOrphanedItems(db);
577 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700578 }
579
Kenny Guyed131872014-04-30 03:02:21 +0100580 if (version < 20) {
581 // Add userId column
582 if (addProfileColumn(db)) {
583 version = 20;
584 }
585 // else old version remains, which means we wipe old data
586 }
587
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800588 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800589 Log.w(TAG, "Destroying all old data.");
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800590 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800591 }
592 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800593
Adam Cohen9b1d0622014-05-21 19:01:57 -0700594 @Override
595 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
596 // This shouldn't happen -- throw our hands up in the air and start over.
597 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
598 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700599 createEmptyDB(db);
600 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700601
Sunny Goyal42de82f2014-09-26 22:09:29 -0700602
603 /**
604 * Clears all the data for a fresh start.
605 */
606 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700607 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
608 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
609 onCreate(db);
610 }
611
Kenny Guyed131872014-04-30 03:02:21 +0100612 private boolean addProfileColumn(SQLiteDatabase db) {
613 db.beginTransaction();
614 try {
615 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
616 // Default to the serial number of this user, for older
617 // shortcuts.
618 long userSerialNumber = userManager.getSerialNumberForUser(
619 UserHandleCompat.myUserHandle());
620 // Insert new column for holding user serial number
621 db.execSQL("ALTER TABLE favorites " +
622 "ADD COLUMN profileId INTEGER DEFAULT "
623 + userSerialNumber + ";");
624 db.setTransactionSuccessful();
625 } catch (SQLException ex) {
626 // Old version remains, which means we wipe old data
627 Log.e(TAG, ex.getMessage(), ex);
628 return false;
629 } finally {
630 db.endTransaction();
631 }
632 return true;
633 }
634
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700635 // Generates a new ID to use for an object in your database. This method should be only
636 // called from the main UI thread. As an exception, we do call it when we call the
637 // constructor from the worker thread; however, this doesn't extend until after the
638 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
639 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700640 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700641 public long generateNewItemId() {
642 if (mMaxItemId < 0) {
643 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700644 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700645 mMaxItemId += 1;
646 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700647 }
648
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700649 @Override
650 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
651 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
652 }
653
Winson Chungc763c4e2013-07-19 13:49:06 -0700654 public void updateMaxItemId(long id) {
655 mMaxItemId = id + 1;
656 }
657
Chris Wren5dee7af2013-12-20 17:22:11 -0500658 public void checkId(String table, ContentValues values) {
659 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
660 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
661 mMaxScreenId = Math.max(id, mMaxScreenId);
662 } else {
663 mMaxItemId = Math.max(id, mMaxItemId);
664 }
665 }
666
Adam Cohendcd297f2013-06-18 13:13:40 -0700667 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700668 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
669
670 // get the result
671 final int maxIdIndex = 0;
672 long id = -1;
673 if (c != null && c.moveToNext()) {
674 id = c.getLong(maxIdIndex);
675 }
Michael Jurka5130e402011-10-13 04:55:35 -0700676 if (c != null) {
677 c.close();
678 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700679
680 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700681 throw new RuntimeException("Error: could not query max item id");
682 }
683
684 return id;
685 }
686
687 // Generates a new ID to use for an workspace screen in your database. This method
688 // should be only called from the main UI thread. As an exception, we do call it when we
689 // call the constructor from the worker thread; however, this doesn't extend until after the
690 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
691 // after that point
692 public long generateNewScreenId() {
693 if (mMaxScreenId < 0) {
694 throw new RuntimeException("Error: max screen id was not initialized");
695 }
696 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800697 // Log to disk
698 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700699 return mMaxScreenId;
700 }
701
702 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800703 // Log to disk
704 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700705 mMaxScreenId = maxScreenId;
706 }
707
708 private long initializeMaxScreenId(SQLiteDatabase db) {
709 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
710
711 // get the result
712 final int maxIdIndex = 0;
713 long id = -1;
714 if (c != null && c.moveToNext()) {
715 id = c.getLong(maxIdIndex);
716 }
717 if (c != null) {
718 c.close();
719 }
720
721 if (id == -1) {
722 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700723 }
724
Winson Chunga90303b2013-11-15 13:05:06 -0800725 // Log to disk
726 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700727 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800728 }
729
Adam Cohena043fa82014-07-23 14:49:38 -0700730 private boolean initializeExternalAdd(ContentValues values) {
731 // 1. Ensure that externally added items have a valid item id
732 long id = generateNewItemId();
733 values.put(LauncherSettings.Favorites._ID, id);
734
735 // 2. In the case of an app widget, and if no app widget id is specified, we
736 // attempt allocate and bind the widget.
737 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
738 if (itemType != null &&
739 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
740 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
741
742 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
743 ComponentName cn = ComponentName.unflattenFromString(
744 values.getAsString(Favorites.APPWIDGET_PROVIDER));
745
746 if (cn != null) {
747 try {
748 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700749 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700750 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700751 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700752 }
753 } catch (RuntimeException e) {
754 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700755 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700756 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700757 } else {
758 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700759 }
760 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700761
762 // Add screen id if not present
763 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
764 if (!addScreenIdIfNecessary(screenId)) {
765 return false;
766 }
Adam Cohena043fa82014-07-23 14:49:38 -0700767 return true;
768 }
769
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700770 // Returns true of screen id exists, or if successfully added
771 private boolean addScreenIdIfNecessary(long screenId) {
772 if (!hasScreenId(screenId)) {
773 int rank = getMaxScreenRank() + 1;
774
775 ContentValues v = new ContentValues();
776 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
777 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
778 if (dbInsertAndCheck(this, getWritableDatabase(),
779 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
780 return false;
781 }
782 }
783 return true;
784 }
785
786 private boolean hasScreenId(long screenId) {
787 SQLiteDatabase db = getWritableDatabase();
788 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
789 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
790 if (c != null) {
791 int count = c.getCount();
792 c.close();
793 return count > 0;
794 } else {
795 return false;
796 }
797 }
798
799 private int getMaxScreenRank() {
800 SQLiteDatabase db = getWritableDatabase();
801 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
802 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
803
804 // get the result
805 final int maxRankIndex = 0;
806 int rank = -1;
807 if (c != null && c.moveToNext()) {
808 rank = c.getInt(maxRankIndex);
809 }
810 if (c != null) {
811 c.close();
812 }
813
814 return rank;
815 }
816
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700817 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700818 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700819 // TODO: Use multiple loaders with fall-back and transaction.
820 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700821
822 // Add the screens specified by the items above
823 Collections.sort(screenIds);
824 int rank = 0;
825 ContentValues values = new ContentValues();
826 for (Long id : screenIds) {
827 values.clear();
828 values.put(LauncherSettings.WorkspaceScreens._ID, id);
829 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
830 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
831 throw new RuntimeException("Failed initialize screen table"
832 + "from default layout");
833 }
834 rank++;
835 }
836
837 // Ensure that the max ids are initialized
838 mMaxItemId = initializeMaxItemId(db);
839 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700840
Adam Cohen71483f42014-05-15 14:04:01 -0700841 return count;
842 }
843
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700844 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500845 final ContentResolver resolver = mContext.getContentResolver();
846 Cursor c = null;
847 int count = 0;
848 int curScreen = 0;
849
850 try {
851 c = resolver.query(uri, null, null, null, "title ASC");
852 } catch (Exception e) {
853 // Ignore
854 }
855
Dan Sandlerd5024042014-01-09 15:01:33 -0500856 // We already have a favorites database in the old provider
857 if (c != null) {
858 try {
859 if (c.getCount() > 0) {
860 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
861 final int intentIndex
862 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
863 final int titleIndex
864 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
865 final int iconTypeIndex
866 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
867 final int iconIndex
868 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
869 final int iconPackageIndex
870 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
871 final int iconResourceIndex
872 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
873 final int containerIndex
874 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
875 final int itemTypeIndex
876 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
877 final int screenIndex
878 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
879 final int cellXIndex
880 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
881 final int cellYIndex
882 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
883 final int uriIndex
884 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
885 final int displayModeIndex
886 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100887 final int profileIndex
888 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500889
890 int i = 0;
891 int curX = 0;
892 int curY = 0;
893
894 final LauncherAppState app = LauncherAppState.getInstance();
895 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
896 final int width = (int) grid.numColumns;
897 final int height = (int) grid.numRows;
898 final int hotseatWidth = (int) grid.numHotseatIcons;
899
900 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
901
Adam Cohen72960972014-01-15 18:13:55 -0800902 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
903 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500904 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500905
906 while (c.moveToNext()) {
907 final int itemType = c.getInt(itemTypeIndex);
908 if (itemType != Favorites.ITEM_TYPE_APPLICATION
909 && itemType != Favorites.ITEM_TYPE_SHORTCUT
910 && itemType != Favorites.ITEM_TYPE_FOLDER) {
911 continue;
912 }
913
914 final int cellX = c.getInt(cellXIndex);
915 final int cellY = c.getInt(cellYIndex);
916 final int screen = c.getInt(screenIndex);
917 int container = c.getInt(containerIndex);
918 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100919
920 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
921 UserHandleCompat userHandle;
922 final long userSerialNumber;
923 if (profileIndex != -1 && !c.isNull(profileIndex)) {
924 userSerialNumber = c.getInt(profileIndex);
925 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
926 } else {
927 // Default to the serial number of this user, for older
928 // shortcuts.
929 userHandle = UserHandleCompat.myUserHandle();
930 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
931 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800932
933 if (userHandle == null) {
934 Launcher.addDumpLog(TAG, "skipping deleted user", true);
935 continue;
936 }
937
Dan Sandlerd5024042014-01-09 15:01:33 -0500938 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500939 + c.getString(titleIndex) + "\" ("
940 + cellX + "," + cellY + "@"
941 + LauncherSettings.Favorites.containerToString(container)
942 + "/" + screen
943 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500944
945 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800946
947 final Intent intent;
948 final ComponentName cn;
949 try {
950 intent = Intent.parseUri(intentStr, 0);
951 } catch (URISyntaxException e) {
952 // bogus intent?
953 Launcher.addDumpLog(TAG,
954 "skipping invalid intent uri", true);
955 continue;
956 }
957
958 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500959 if (TextUtils.isEmpty(intentStr)) {
960 // no intent? no icon
961 Launcher.addDumpLog(TAG, "skipping empty intent", true);
962 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800963 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100964 !LauncherModel.isValidPackageActivity(mContext, cn,
965 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800966 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800967 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -0800968 "no longer exists.", true);
969 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800970 } else if (container ==
971 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
972 // Dedupe icons directly on the workspace
973
Adam Cohen556f6132014-01-15 15:18:08 -0800974 // Canonicalize
975 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -0700976 // does not, so we clear that out to keep them the same.
977 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -0800978 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -0700979 int flags = intent.getFlags();
980 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -0800981 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -0700982 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -0800983 if (seenIntents.contains(key)) {
984 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500985 continue;
Adam Cohen556f6132014-01-15 15:18:08 -0800986 } else {
987 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -0500988 }
989 }
990 }
991
992 ContentValues values = new ContentValues(c.getColumnCount());
993 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
994 values.put(LauncherSettings.Favorites.INTENT, intentStr);
995 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
996 values.put(LauncherSettings.Favorites.ICON_TYPE,
997 c.getInt(iconTypeIndex));
998 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
999 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1000 c.getString(iconPackageIndex));
1001 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1002 c.getString(iconResourceIndex));
1003 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1004 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1005 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1006 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1007 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001008 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001009
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001010 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1011 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001012 }
1013
1014 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1015 // In a folder or in the hotseat, preserve position
1016 values.put(LauncherSettings.Favorites.SCREEN, screen);
1017 values.put(LauncherSettings.Favorites.CELLX, cellX);
1018 values.put(LauncherSettings.Favorites.CELLY, cellY);
1019 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001020 // For items contained directly on one of the workspace screen,
1021 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001022 }
1023
1024 values.put(LauncherSettings.Favorites.CONTAINER, container);
1025
Adam Cohen72960972014-01-15 18:13:55 -08001026 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1027 shortcuts.add(values);
1028 } else {
1029 folders.add(values);
1030 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001031 }
1032
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001033 // Now that we have all the hotseat icons, let's go through them left-right
1034 // and assign valid locations for them in the new hotseat
1035 final int N = hotseat.size();
1036 for (int idx=0; idx<N; idx++) {
1037 int hotseatX = hotseat.keyAt(idx);
1038 ContentValues values = hotseat.valueAt(idx);
1039
1040 if (hotseatX == grid.hotseatAllAppsRank) {
1041 // let's drop this in the next available hole in the hotseat
1042 while (++hotseatX < hotseatWidth) {
1043 if (hotseat.get(hotseatX) == null) {
1044 // found a spot! move it here
1045 values.put(LauncherSettings.Favorites.SCREEN,
1046 hotseatX);
1047 break;
1048 }
1049 }
1050 }
1051 if (hotseatX >= hotseatWidth) {
1052 // no room for you in the hotseat? it's off to the desktop with you
1053 values.put(LauncherSettings.Favorites.CONTAINER,
1054 Favorites.CONTAINER_DESKTOP);
1055 }
1056 }
1057
Adam Cohen72960972014-01-15 18:13:55 -08001058 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1059 // Folders first
1060 allItems.addAll(folders);
1061 // Then shortcuts
1062 allItems.addAll(shortcuts);
1063
1064 // Layout all the folders
1065 for (ContentValues values: allItems) {
1066 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1067 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1068 // Hotseat items and folder items have already had their
1069 // location information set. Nothing to be done here.
1070 continue;
1071 }
1072 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1073 values.put(LauncherSettings.Favorites.CELLX, curX);
1074 values.put(LauncherSettings.Favorites.CELLY, curY);
1075 curX = (curX + 1) % width;
1076 if (curX == 0) {
1077 curY = (curY + 1);
1078 }
1079 // Leave the last row of icons blank on every screen
1080 if (curY == height - 1) {
1081 curScreen = (int) generateNewScreenId();
1082 curY = 0;
1083 }
1084 }
1085
1086 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001087 db.beginTransaction();
1088 try {
Adam Cohen72960972014-01-15 18:13:55 -08001089 for (ContentValues row: allItems) {
1090 if (row == null) continue;
1091 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001092 < 0) {
1093 return;
1094 } else {
1095 count++;
1096 }
1097 }
1098 db.setTransactionSuccessful();
1099 } finally {
1100 db.endTransaction();
1101 }
1102 }
1103
1104 db.beginTransaction();
1105 try {
1106 for (i=0; i<=curScreen; i++) {
1107 final ContentValues values = new ContentValues();
1108 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1109 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1110 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1111 < 0) {
1112 return;
1113 }
1114 }
1115 db.setTransactionSuccessful();
1116 } finally {
1117 db.endTransaction();
1118 }
1119 }
1120 } finally {
1121 c.close();
1122 }
1123 }
1124
1125 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1126 + (curScreen+1) + " screens", true);
1127
1128 // ensure that new screens are created to hold these icons
1129 setFlagJustLoadedOldDb();
1130
1131 // Update max IDs; very important since we just grabbed IDs from another database
1132 mMaxItemId = initializeMaxItemId(db);
1133 mMaxScreenId = initializeMaxScreenId(db);
1134 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1135 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001136 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 static class SqlArguments {
1139 public final String table;
1140 public final String where;
1141 public final String[] args;
1142
1143 SqlArguments(Uri url, String where, String[] args) {
1144 if (url.getPathSegments().size() == 1) {
1145 this.table = url.getPathSegments().get(0);
1146 this.where = where;
1147 this.args = args;
1148 } else if (url.getPathSegments().size() != 2) {
1149 throw new IllegalArgumentException("Invalid URI: " + url);
1150 } else if (!TextUtils.isEmpty(where)) {
1151 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1152 } else {
1153 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001154 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001155 this.args = null;
1156 }
1157 }
1158
1159 SqlArguments(Uri url) {
1160 if (url.getPathSegments().size() == 1) {
1161 table = url.getPathSegments().get(0);
1162 where = null;
1163 args = null;
1164 } else {
1165 throw new IllegalArgumentException("Invalid URI: " + url);
1166 }
1167 }
1168 }
Adam Cohen72960972014-01-15 18:13:55 -08001169}