blob: a9ad596525b0cbbe20a533a30e0526a774946ad0 [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;
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 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
Sunny Goyal08f72612015-01-05 13:41:43 -0800329 public void updateFolderItemsRank() {
330 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
331 }
332
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 public void deleteDatabase() {
334 // Are you sure? (y/n)
335 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500336 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500337 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500338 if (dbFile.exists()) {
339 SQLiteDatabase.deleteDatabase(dbFile);
340 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500341 mOpenHelper = new DatabaseHelper(getContext());
342 }
343
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700344 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700346 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700347 private long mMaxItemId = -1;
348 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349
Winson Chung0b560dd2014-01-21 13:00:26 -0800350 private boolean mNewDbCreated = false;
351
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100353 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700355 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700356
357 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
358 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700359 if (mMaxItemId == -1) {
360 mMaxItemId = initializeMaxItemId(getWritableDatabase());
361 }
362 if (mMaxScreenId == -1) {
363 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700364 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800365 }
366
Winson Chung0b560dd2014-01-21 13:00:26 -0800367 public boolean wasNewDbCreated() {
368 return mNewDbCreated;
369 }
370
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700371 /**
372 * Send notification that we've deleted the {@link AppWidgetHost},
373 * probably as part of the initial database creation. The receiver may
374 * want to re-call {@link AppWidgetHost#startListening()} to ensure
375 * callbacks are correctly set.
376 */
377 private void sendAppWidgetResetNotify() {
378 final ContentResolver resolver = mContext.getContentResolver();
379 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
380 }
381
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800382 @Override
383 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800384 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700385
Adam Cohendcd297f2013-06-18 13:13:40 -0700386 mMaxItemId = 1;
387 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800388 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700389
Kenny Guyed131872014-04-30 03:02:21 +0100390 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
391 long userSerialNumber = userManager.getSerialNumberForUser(
392 UserHandleCompat.myUserHandle());
393
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 db.execSQL("CREATE TABLE favorites (" +
395 "_id INTEGER PRIMARY KEY," +
396 "title TEXT," +
397 "intent TEXT," +
398 "container INTEGER," +
399 "screen INTEGER," +
400 "cellX INTEGER," +
401 "cellY INTEGER," +
402 "spanX INTEGER," +
403 "spanY INTEGER," +
404 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700405 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800406 "isShortcut INTEGER," +
407 "iconType INTEGER," +
408 "iconPackage TEXT," +
409 "iconResource TEXT," +
410 "icon BLOB," +
411 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400412 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400413 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500414 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100415 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800416 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
417 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800418 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700419 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800420
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700421 // Database was just created, so wipe any previous widgets
422 if (mAppWidgetHost != null) {
423 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700424 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700426
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800427 // Fresh and clean launcher DB.
428 mMaxItemId = initializeMaxItemId(db);
429 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800430 }
431
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 private void addWorkspacesTable(SQLiteDatabase db) {
433 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
434 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400435 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
436 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700437 ");");
438 }
439
Adam Cohen119285e2014-04-02 16:59:08 -0700440 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700441 // Delete items directly on the workspace who's screen id doesn't exist
442 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
443 // AND container = -100"
444 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
445 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700446 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700447 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
448 " AND " +
449 LauncherSettings.Favorites.CONTAINER + " = " +
450 LauncherSettings.Favorites.CONTAINER_DESKTOP;
451 db.execSQL(removeOrphanedDesktopItems);
452
453 // Delete items contained in folders which no longer exist (after above statement)
454 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
455 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
456 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
457 " WHERE " +
458 LauncherSettings.Favorites.CONTAINER + " <> " +
459 LauncherSettings.Favorites.CONTAINER_DESKTOP +
460 " AND "
461 + LauncherSettings.Favorites.CONTAINER + " <> " +
462 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
463 " AND "
464 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
465 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
466 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
467 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
468 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700469 }
470
Winson Chungc763c4e2013-07-19 13:49:06 -0700471 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400472 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700473 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
474 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700475 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
476 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700477 editor.commit();
478 }
479
Winson Chungc763c4e2013-07-19 13:49:06 -0700480 private void setFlagEmptyDbCreated() {
481 String spKey = LauncherAppState.getSharedPreferencesKey();
482 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
483 SharedPreferences.Editor editor = sp.edit();
484 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
485 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
486 editor.commit();
487 }
488
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800489 @Override
490 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700491 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700492
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800493 int version = oldVersion;
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800494 if (version < MIN_DATABASE_VERSION) {
495 // The version cannot be lower that this, as Launcher3 never supported a lower
496 // version of the DB.
497 createEmptyDB(db);
498 version = DATABASE_VERSION;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700499 }
500
Adam Cohendcd297f2013-06-18 13:13:40 -0700501 if (version < 13) {
502 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
503 // to persist workspace screens and their relative order.
504 mMaxScreenId = 0;
505
Adam Cohendcd297f2013-06-18 13:13:40 -0700506 addWorkspacesTable(db);
507 version = 13;
508 }
509
Chris Wrend5e66bf2013-09-16 14:02:29 -0400510 if (version < 14) {
511 db.beginTransaction();
512 try {
513 // Insert new column for holding widget provider name
514 db.execSQL("ALTER TABLE favorites " +
515 "ADD COLUMN appWidgetProvider TEXT;");
516 db.setTransactionSuccessful();
517 version = 14;
518 } catch (SQLException ex) {
519 // Old version remains, which means we wipe old data
520 Log.e(TAG, ex.getMessage(), ex);
521 } finally {
522 db.endTransaction();
523 }
524 }
525
Chris Wren1ada10d2013-09-13 18:01:38 -0400526 if (version < 15) {
527 db.beginTransaction();
528 try {
529 // Insert new column for holding update timestamp
530 db.execSQL("ALTER TABLE favorites " +
531 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
532 db.execSQL("ALTER TABLE workspaceScreens " +
533 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
534 db.setTransactionSuccessful();
535 version = 15;
536 } catch (SQLException ex) {
537 // Old version remains, which means we wipe old data
538 Log.e(TAG, ex.getMessage(), ex);
539 } finally {
540 db.endTransaction();
541 }
542 }
543
Chris Wrenf4d08112014-01-16 18:13:56 -0500544
545 if (version < 16) {
546 db.beginTransaction();
547 try {
548 // Insert new column for holding restore status
549 db.execSQL("ALTER TABLE favorites " +
550 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
551 db.setTransactionSuccessful();
552 version = 16;
553 } catch (SQLException ex) {
554 // Old version remains, which means we wipe old data
555 Log.e(TAG, ex.getMessage(), ex);
556 } finally {
557 db.endTransaction();
558 }
559 }
560
Adam Cohen71e03b92014-02-21 14:09:53 -0800561 if (version < 17) {
562 // We use the db version upgrade here to identify users who may not have seen
563 // clings yet (because they weren't available), but for whom the clings are now
564 // available (tablet users). Because one of the possible cling flows (migration)
565 // is very destructive (wipes out workspaces), we want to prevent this from showing
566 // until clear data. We do so by marking that the clings have been shown.
567 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
568 version = 17;
569 }
570
Adam Cohen119285e2014-04-02 16:59:08 -0700571 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700572 // No-op
573 version = 18;
574 }
575
576 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700577 // Due to a data loss bug, some users may have items associated with screen ids
578 // which no longer exist. Since this can cause other problems, and since the user
579 // will never see these items anyway, we use database upgrade as an opportunity to
580 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700581 removeOrphanedItems(db);
582 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700583 }
584
Kenny Guyed131872014-04-30 03:02:21 +0100585 if (version < 20) {
586 // Add userId column
587 if (addProfileColumn(db)) {
588 version = 20;
589 }
590 // else old version remains, which means we wipe old data
591 }
592
Sunny Goyal08f72612015-01-05 13:41:43 -0800593 if (version < 21) {
594 if (updateFolderItemsRank(db, true)) {
595 version = 21;
596 }
597 }
598
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800600 Log.w(TAG, "Destroying all old data.");
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800601 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 }
603 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800604
Adam Cohen9b1d0622014-05-21 19:01:57 -0700605 @Override
606 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
607 // This shouldn't happen -- throw our hands up in the air and start over.
608 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
609 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700610 createEmptyDB(db);
611 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700612
Sunny Goyal42de82f2014-09-26 22:09:29 -0700613
614 /**
615 * Clears all the data for a fresh start.
616 */
617 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700618 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
619 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
620 onCreate(db);
621 }
622
Sunny Goyal08f72612015-01-05 13:41:43 -0800623 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
624 db.beginTransaction();
625 try {
626 if (addRankColumn) {
627 // Insert new column for holding rank
628 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
629 }
630
631 // Get a map for folder ID to folder width
632 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
633 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
634 + " GROUP BY container;",
635 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
636
637 while (c.moveToNext()) {
638 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE container=?;",
639 new Object[] {c.getLong(1) + 1, c.getLong(0)});
640 }
641
642 c.close();
643 db.setTransactionSuccessful();
644 } catch (SQLException ex) {
645 // Old version remains, which means we wipe old data
646 Log.e(TAG, ex.getMessage(), ex);
647 return false;
648 } finally {
649 db.endTransaction();
650 }
651 return true;
652 }
653
Kenny Guyed131872014-04-30 03:02:21 +0100654 private boolean addProfileColumn(SQLiteDatabase db) {
655 db.beginTransaction();
656 try {
657 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
658 // Default to the serial number of this user, for older
659 // shortcuts.
660 long userSerialNumber = userManager.getSerialNumberForUser(
661 UserHandleCompat.myUserHandle());
662 // Insert new column for holding user serial number
663 db.execSQL("ALTER TABLE favorites " +
664 "ADD COLUMN profileId INTEGER DEFAULT "
665 + userSerialNumber + ";");
666 db.setTransactionSuccessful();
667 } catch (SQLException ex) {
668 // Old version remains, which means we wipe old data
669 Log.e(TAG, ex.getMessage(), ex);
670 return false;
671 } finally {
672 db.endTransaction();
673 }
674 return true;
675 }
676
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700677 // Generates a new ID to use for an object in your database. This method should be only
678 // called from the main UI thread. As an exception, we do call it when we call the
679 // constructor from the worker thread; however, this doesn't extend until after the
680 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
681 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700682 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700683 public long generateNewItemId() {
684 if (mMaxItemId < 0) {
685 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700686 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700687 mMaxItemId += 1;
688 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700689 }
690
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700691 @Override
692 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
693 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
694 }
695
Winson Chungc763c4e2013-07-19 13:49:06 -0700696 public void updateMaxItemId(long id) {
697 mMaxItemId = id + 1;
698 }
699
Chris Wren5dee7af2013-12-20 17:22:11 -0500700 public void checkId(String table, ContentValues values) {
701 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
702 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
703 mMaxScreenId = Math.max(id, mMaxScreenId);
704 } else {
705 mMaxItemId = Math.max(id, mMaxItemId);
706 }
707 }
708
Adam Cohendcd297f2013-06-18 13:13:40 -0700709 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700710 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
711
712 // get the result
713 final int maxIdIndex = 0;
714 long id = -1;
715 if (c != null && c.moveToNext()) {
716 id = c.getLong(maxIdIndex);
717 }
Michael Jurka5130e402011-10-13 04:55:35 -0700718 if (c != null) {
719 c.close();
720 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700721
722 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700723 throw new RuntimeException("Error: could not query max item id");
724 }
725
726 return id;
727 }
728
729 // Generates a new ID to use for an workspace screen in your database. This method
730 // should be only called from the main UI thread. As an exception, we do call it when we
731 // call the constructor from the worker thread; however, this doesn't extend until after the
732 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
733 // after that point
734 public long generateNewScreenId() {
735 if (mMaxScreenId < 0) {
736 throw new RuntimeException("Error: max screen id was not initialized");
737 }
738 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800739 // Log to disk
740 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700741 return mMaxScreenId;
742 }
743
744 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800745 // Log to disk
746 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700747 mMaxScreenId = maxScreenId;
748 }
749
750 private long initializeMaxScreenId(SQLiteDatabase db) {
751 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
752
753 // get the result
754 final int maxIdIndex = 0;
755 long id = -1;
756 if (c != null && c.moveToNext()) {
757 id = c.getLong(maxIdIndex);
758 }
759 if (c != null) {
760 c.close();
761 }
762
763 if (id == -1) {
764 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700765 }
766
Winson Chunga90303b2013-11-15 13:05:06 -0800767 // Log to disk
768 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700769 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800770 }
771
Adam Cohena043fa82014-07-23 14:49:38 -0700772 private boolean initializeExternalAdd(ContentValues values) {
773 // 1. Ensure that externally added items have a valid item id
774 long id = generateNewItemId();
775 values.put(LauncherSettings.Favorites._ID, id);
776
777 // 2. In the case of an app widget, and if no app widget id is specified, we
778 // attempt allocate and bind the widget.
779 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
780 if (itemType != null &&
781 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
782 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
783
784 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
785 ComponentName cn = ComponentName.unflattenFromString(
786 values.getAsString(Favorites.APPWIDGET_PROVIDER));
787
788 if (cn != null) {
789 try {
790 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700791 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700792 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700793 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700794 }
795 } catch (RuntimeException e) {
796 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700797 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700798 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700799 } else {
800 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700801 }
802 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700803
804 // Add screen id if not present
805 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
806 if (!addScreenIdIfNecessary(screenId)) {
807 return false;
808 }
Adam Cohena043fa82014-07-23 14:49:38 -0700809 return true;
810 }
811
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700812 // Returns true of screen id exists, or if successfully added
813 private boolean addScreenIdIfNecessary(long screenId) {
814 if (!hasScreenId(screenId)) {
815 int rank = getMaxScreenRank() + 1;
816
817 ContentValues v = new ContentValues();
818 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
819 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
820 if (dbInsertAndCheck(this, getWritableDatabase(),
821 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
822 return false;
823 }
824 }
825 return true;
826 }
827
828 private boolean hasScreenId(long screenId) {
829 SQLiteDatabase db = getWritableDatabase();
830 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
831 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
832 if (c != null) {
833 int count = c.getCount();
834 c.close();
835 return count > 0;
836 } else {
837 return false;
838 }
839 }
840
841 private int getMaxScreenRank() {
842 SQLiteDatabase db = getWritableDatabase();
843 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
844 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
845
846 // get the result
847 final int maxRankIndex = 0;
848 int rank = -1;
849 if (c != null && c.moveToNext()) {
850 rank = c.getInt(maxRankIndex);
851 }
852 if (c != null) {
853 c.close();
854 }
855
856 return rank;
857 }
858
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700859 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700860 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700861 // TODO: Use multiple loaders with fall-back and transaction.
862 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700863
864 // Add the screens specified by the items above
865 Collections.sort(screenIds);
866 int rank = 0;
867 ContentValues values = new ContentValues();
868 for (Long id : screenIds) {
869 values.clear();
870 values.put(LauncherSettings.WorkspaceScreens._ID, id);
871 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
872 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
873 throw new RuntimeException("Failed initialize screen table"
874 + "from default layout");
875 }
876 rank++;
877 }
878
879 // Ensure that the max ids are initialized
880 mMaxItemId = initializeMaxItemId(db);
881 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700882
Adam Cohen71483f42014-05-15 14:04:01 -0700883 return count;
884 }
885
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700886 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500887 final ContentResolver resolver = mContext.getContentResolver();
888 Cursor c = null;
889 int count = 0;
890 int curScreen = 0;
891
892 try {
893 c = resolver.query(uri, null, null, null, "title ASC");
894 } catch (Exception e) {
895 // Ignore
896 }
897
Dan Sandlerd5024042014-01-09 15:01:33 -0500898 // We already have a favorites database in the old provider
899 if (c != null) {
900 try {
901 if (c.getCount() > 0) {
902 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
903 final int intentIndex
904 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
905 final int titleIndex
906 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
907 final int iconTypeIndex
908 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
909 final int iconIndex
910 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
911 final int iconPackageIndex
912 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
913 final int iconResourceIndex
914 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
915 final int containerIndex
916 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
917 final int itemTypeIndex
918 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
919 final int screenIndex
920 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
921 final int cellXIndex
922 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
923 final int cellYIndex
924 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
925 final int uriIndex
926 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
927 final int displayModeIndex
928 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100929 final int profileIndex
930 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500931
932 int i = 0;
933 int curX = 0;
934 int curY = 0;
935
936 final LauncherAppState app = LauncherAppState.getInstance();
937 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
938 final int width = (int) grid.numColumns;
939 final int height = (int) grid.numRows;
940 final int hotseatWidth = (int) grid.numHotseatIcons;
941
942 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
943
Adam Cohen72960972014-01-15 18:13:55 -0800944 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
945 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500946 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500947
948 while (c.moveToNext()) {
949 final int itemType = c.getInt(itemTypeIndex);
950 if (itemType != Favorites.ITEM_TYPE_APPLICATION
951 && itemType != Favorites.ITEM_TYPE_SHORTCUT
952 && itemType != Favorites.ITEM_TYPE_FOLDER) {
953 continue;
954 }
955
956 final int cellX = c.getInt(cellXIndex);
957 final int cellY = c.getInt(cellYIndex);
958 final int screen = c.getInt(screenIndex);
959 int container = c.getInt(containerIndex);
960 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100961
962 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
963 UserHandleCompat userHandle;
964 final long userSerialNumber;
965 if (profileIndex != -1 && !c.isNull(profileIndex)) {
966 userSerialNumber = c.getInt(profileIndex);
967 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
968 } else {
969 // Default to the serial number of this user, for older
970 // shortcuts.
971 userHandle = UserHandleCompat.myUserHandle();
972 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
973 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800974
975 if (userHandle == null) {
976 Launcher.addDumpLog(TAG, "skipping deleted user", true);
977 continue;
978 }
979
Dan Sandlerd5024042014-01-09 15:01:33 -0500980 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500981 + c.getString(titleIndex) + "\" ("
982 + cellX + "," + cellY + "@"
983 + LauncherSettings.Favorites.containerToString(container)
984 + "/" + screen
985 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500986
987 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800988
989 final Intent intent;
990 final ComponentName cn;
991 try {
992 intent = Intent.parseUri(intentStr, 0);
993 } catch (URISyntaxException e) {
994 // bogus intent?
995 Launcher.addDumpLog(TAG,
996 "skipping invalid intent uri", true);
997 continue;
998 }
999
1000 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001001 if (TextUtils.isEmpty(intentStr)) {
1002 // no intent? no icon
1003 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1004 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001005 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001006 !LauncherModel.isValidPackageActivity(mContext, cn,
1007 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001008 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001009 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001010 "no longer exists.", true);
1011 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001012 } else if (container ==
1013 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1014 // Dedupe icons directly on the workspace
1015
Adam Cohen556f6132014-01-15 15:18:08 -08001016 // Canonicalize
1017 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001018 // does not, so we clear that out to keep them the same.
1019 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001020 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001021 int flags = intent.getFlags();
1022 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001023 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001024 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001025 if (seenIntents.contains(key)) {
1026 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001027 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001028 } else {
1029 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001030 }
1031 }
1032 }
1033
1034 ContentValues values = new ContentValues(c.getColumnCount());
1035 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1036 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1037 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1038 values.put(LauncherSettings.Favorites.ICON_TYPE,
1039 c.getInt(iconTypeIndex));
1040 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1041 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1042 c.getString(iconPackageIndex));
1043 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1044 c.getString(iconResourceIndex));
1045 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1046 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1047 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1048 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1049 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001050 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001051
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001052 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1053 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001054 }
1055
1056 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1057 // In a folder or in the hotseat, preserve position
1058 values.put(LauncherSettings.Favorites.SCREEN, screen);
1059 values.put(LauncherSettings.Favorites.CELLX, cellX);
1060 values.put(LauncherSettings.Favorites.CELLY, cellY);
1061 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001062 // For items contained directly on one of the workspace screen,
1063 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001064 }
1065
1066 values.put(LauncherSettings.Favorites.CONTAINER, container);
1067
Adam Cohen72960972014-01-15 18:13:55 -08001068 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1069 shortcuts.add(values);
1070 } else {
1071 folders.add(values);
1072 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001073 }
1074
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001075 // Now that we have all the hotseat icons, let's go through them left-right
1076 // and assign valid locations for them in the new hotseat
1077 final int N = hotseat.size();
1078 for (int idx=0; idx<N; idx++) {
1079 int hotseatX = hotseat.keyAt(idx);
1080 ContentValues values = hotseat.valueAt(idx);
1081
1082 if (hotseatX == grid.hotseatAllAppsRank) {
1083 // let's drop this in the next available hole in the hotseat
1084 while (++hotseatX < hotseatWidth) {
1085 if (hotseat.get(hotseatX) == null) {
1086 // found a spot! move it here
1087 values.put(LauncherSettings.Favorites.SCREEN,
1088 hotseatX);
1089 break;
1090 }
1091 }
1092 }
1093 if (hotseatX >= hotseatWidth) {
1094 // no room for you in the hotseat? it's off to the desktop with you
1095 values.put(LauncherSettings.Favorites.CONTAINER,
1096 Favorites.CONTAINER_DESKTOP);
1097 }
1098 }
1099
Adam Cohen72960972014-01-15 18:13:55 -08001100 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1101 // Folders first
1102 allItems.addAll(folders);
1103 // Then shortcuts
1104 allItems.addAll(shortcuts);
1105
1106 // Layout all the folders
1107 for (ContentValues values: allItems) {
1108 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1109 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1110 // Hotseat items and folder items have already had their
1111 // location information set. Nothing to be done here.
1112 continue;
1113 }
1114 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1115 values.put(LauncherSettings.Favorites.CELLX, curX);
1116 values.put(LauncherSettings.Favorites.CELLY, curY);
1117 curX = (curX + 1) % width;
1118 if (curX == 0) {
1119 curY = (curY + 1);
1120 }
1121 // Leave the last row of icons blank on every screen
1122 if (curY == height - 1) {
1123 curScreen = (int) generateNewScreenId();
1124 curY = 0;
1125 }
1126 }
1127
1128 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001129 db.beginTransaction();
1130 try {
Adam Cohen72960972014-01-15 18:13:55 -08001131 for (ContentValues row: allItems) {
1132 if (row == null) continue;
1133 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001134 < 0) {
1135 return;
1136 } else {
1137 count++;
1138 }
1139 }
1140 db.setTransactionSuccessful();
1141 } finally {
1142 db.endTransaction();
1143 }
1144 }
1145
1146 db.beginTransaction();
1147 try {
1148 for (i=0; i<=curScreen; i++) {
1149 final ContentValues values = new ContentValues();
1150 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1151 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1152 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1153 < 0) {
1154 return;
1155 }
1156 }
1157 db.setTransactionSuccessful();
1158 } finally {
1159 db.endTransaction();
1160 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001161
1162 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001163 }
1164 } finally {
1165 c.close();
1166 }
1167 }
1168
1169 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1170 + (curScreen+1) + " screens", true);
1171
1172 // ensure that new screens are created to hold these icons
1173 setFlagJustLoadedOldDb();
1174
1175 // Update max IDs; very important since we just grabbed IDs from another database
1176 mMaxItemId = initializeMaxItemId(db);
1177 mMaxScreenId = initializeMaxScreenId(db);
1178 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1179 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001180 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001181
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001182 static class SqlArguments {
1183 public final String table;
1184 public final String where;
1185 public final String[] args;
1186
1187 SqlArguments(Uri url, String where, String[] args) {
1188 if (url.getPathSegments().size() == 1) {
1189 this.table = url.getPathSegments().get(0);
1190 this.where = where;
1191 this.args = args;
1192 } else if (url.getPathSegments().size() != 2) {
1193 throw new IllegalArgumentException("Invalid URI: " + url);
1194 } else if (!TextUtils.isEmpty(where)) {
1195 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1196 } else {
1197 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001198 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001199 this.args = null;
1200 }
1201 }
1202
1203 SqlArguments(Uri url) {
1204 if (url.getPathSegments().size() == 1) {
1205 table = url.getPathSegments().get(0);
1206 where = null;
1207 args = null;
1208 } else {
1209 throw new IllegalArgumentException("Invalid URI: " + url);
1210 }
1211 }
1212 }
Adam Cohen72960972014-01-15 18:13:55 -08001213}