blob: b7a271e4f6b4633ffd6528167010058805c984c2 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.net.Uri;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080039import android.os.StrictMode;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050042import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070043
Sunny Goyal0fe505b2014-08-06 09:55:36 -070044import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
45import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010046import com.android.launcher3.compat.UserHandleCompat;
47import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040048import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070049
Dan Sandlerd5024042014-01-09 15:01:33 -050050import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070051import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070053import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050054import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080057 private static final String TAG = "Launcher.LauncherProvider";
58 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
Sunny Goyald2f38192015-02-25 10:46:34 -080060 private static final int DATABASE_VERSION = 22;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061
Adam Cohene25af792013-06-06 23:08:25 -070062 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040063 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070066 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080068 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Adam Cohena043fa82014-07-23 14:49:38 -070070 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
71
Anjali Koppal67e7cae2014-03-13 12:14:12 -070072 private LauncherProviderChangeListener mListener;
73
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070074 /**
Romain Guy73b979d2009-06-09 12:57:21 -070075 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070076 * {@link AppWidgetHost#deleteHost()} is called during database creation.
77 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
78 */
79 static final Uri CONTENT_APPWIDGET_RESET_URI =
80 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070081
Michael Jurkaa8c760d2011-04-28 14:59:33 -070082 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080087 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080089 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 return true;
92 }
93
Winson Chung0b560dd2014-01-21 13:00:26 -080094 public boolean wasNewDbCreated() {
95 return mOpenHelper.wasNewDbCreated();
96 }
97
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
99 mListener = listener;
100 }
101
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102 @Override
103 public String getType(Uri uri) {
104 SqlArguments args = new SqlArguments(uri, null, null);
105 if (TextUtils.isEmpty(args.where)) {
106 return "vnd.android.cursor.dir/" + args.table;
107 } else {
108 return "vnd.android.cursor.item/" + args.table;
109 }
110 }
111
112 @Override
113 public Cursor query(Uri uri, String[] projection, String selection,
114 String[] selectionArgs, String sortOrder) {
115
116 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
117 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
118 qb.setTables(args.table);
119
Romain Guy73b979d2009-06-09 12:57:21 -0700120 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
122 result.setNotificationUri(getContext().getContentResolver(), uri);
123
124 return result;
125 }
126
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700127 private static long dbInsertAndCheck(DatabaseHelper helper,
128 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500129 if (values == null) {
130 throw new RuntimeException("Error: attempting to insert null values");
131 }
Adam Cohen71483f42014-05-15 14:04:01 -0700132 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 throw new RuntimeException("Error: attempting to add item without specifying an id");
134 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500135 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700136 return db.insert(table, nullColumnHack, values);
137 }
138
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139 @Override
140 public Uri insert(Uri uri, ContentValues initialValues) {
141 SqlArguments args = new SqlArguments(uri);
142
Adam Cohena043fa82014-07-23 14:49:38 -0700143 // In very limited cases, we support system|signature permission apps to add to the db
144 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
145 if (externalAdd != null && "true".equals(externalAdd)) {
146 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
147 return null;
148 }
149 }
150
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800151 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400152 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800154 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155
156 uri = ContentUris.withAppendedId(uri, rowId);
157 sendNotify(uri);
158
159 return uri;
160 }
161
Adam Cohena043fa82014-07-23 14:49:38 -0700162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public int bulkInsert(Uri uri, ContentValues[] values) {
165 SqlArguments args = new SqlArguments(uri);
166
167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
168 db.beginTransaction();
169 try {
170 int numValues = values.length;
171 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400172 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
174 return 0;
175 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176 }
177 db.setTransactionSuccessful();
178 } finally {
179 db.endTransaction();
180 }
181
182 sendNotify(uri);
183 return values.length;
184 }
185
186 @Override
Yura085c8532014-02-11 15:15:29 +0000187 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
188 throws OperationApplicationException {
189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
190 db.beginTransaction();
191 try {
192 ContentProviderResult[] result = super.applyBatch(operations);
193 db.setTransactionSuccessful();
194 return result;
195 } finally {
196 db.endTransaction();
197 }
198 }
199
200 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 public int delete(Uri uri, String selection, String[] selectionArgs) {
202 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
203
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 int count = db.delete(args.table, args.where, args.args);
206 if (count > 0) sendNotify(uri);
207
208 return count;
209 }
210
211 @Override
212 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
213 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
214
Chris Wren1ada10d2013-09-13 18:01:38 -0400215 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
217 int count = db.update(args.table, values, args.where, args.args);
218 if (count > 0) sendNotify(uri);
219
220 return count;
221 }
222
223 private void sendNotify(Uri uri) {
224 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
225 if (notify == null || "true".equals(notify)) {
226 getContext().getContentResolver().notifyChange(uri, null);
227 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400228
229 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400230 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700231 if (mListener != null) {
232 mListener.onLauncherProviderChange();
233 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400234 }
235
Sunny Goyald2f38192015-02-25 10:46:34 -0800236 private static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400237 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 }
239
Adam Cohendcd297f2013-06-18 13:13:40 -0700240 public long generateNewItemId() {
241 return mOpenHelper.generateNewItemId();
242 }
243
Winson Chungc763c4e2013-07-19 13:49:06 -0700244 public void updateMaxItemId(long id) {
245 mOpenHelper.updateMaxItemId(id);
246 }
247
Adam Cohendcd297f2013-06-18 13:13:40 -0700248 public long generateNewScreenId() {
249 return mOpenHelper.generateNewScreenId();
250 }
251
Brian Muramatsu5524b492012-10-02 16:55:54 -0700252 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700253 * Clears all the data for a fresh start.
254 */
255 synchronized public void createEmptyDB() {
256 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
257 }
258
Sunny Goyal33d44382014-10-16 09:24:19 -0700259 public void clearFlagEmptyDbCreated() {
260 String spKey = LauncherAppState.getSharedPreferencesKey();
261 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
262 .edit()
263 .remove(EMPTY_DATABASE_CREATED)
264 .commit();
265 }
266
Sunny Goyal42de82f2014-09-26 22:09:29 -0700267 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700268 * Loads the default workspace based on the following priority scheme:
269 * 1) From a package provided by play store
270 * 2) From a partner configuration APK, already in the system image
271 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700272 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700273 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400274 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700275 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700276
Winson Chungc763c4e2013-07-19 13:49:06 -0700277 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500278 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200279
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700280 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700281 mOpenHelper.mAppWidgetHost, mOpenHelper);
282
283 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700284 final Partner partner = Partner.get(getContext().getPackageManager());
285 if (partner != null && partner.hasDefaultLayout()) {
286 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700287 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700288 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700289 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700290 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
291 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700292 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700293 }
294 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700295
Sunny Goyal9d219682014-10-23 14:21:02 -0700296 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700297 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700298 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700299 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800300
301 // There might be some partially restored DB items, due to buggy restore logic in
302 // previous versions of launcher.
303 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700304 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700305 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
306 && usingExternallyProvidedLayout) {
307 // Unable to load external layout. Cleanup and load the internal layout.
308 createEmptyDB();
309 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
310 getDefaultLayoutParser());
311 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700312 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700313 }
314 }
315
Sunny Goyal9d219682014-10-23 14:21:02 -0700316 private DefaultLayoutParser getDefaultLayoutParser() {
317 int defaultLayout = LauncherAppState.getInstance()
318 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
319 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
320 mOpenHelper, getContext().getResources(), defaultLayout);
321 }
322
Dan Sandlerd5024042014-01-09 15:01:33 -0500323 public void migrateLauncher2Shortcuts() {
324 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400325 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500326 }
327
Sunny Goyal08f72612015-01-05 13:41:43 -0800328 public void updateFolderItemsRank() {
329 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
330 }
331
Dan Sandlerd5024042014-01-09 15:01:33 -0500332 public void deleteDatabase() {
333 // Are you sure? (y/n)
334 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500335 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500337 if (dbFile.exists()) {
338 SQLiteDatabase.deleteDatabase(dbFile);
339 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500340 mOpenHelper = new DatabaseHelper(getContext());
341 }
342
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700343 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700345 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700346 private long mMaxItemId = -1;
347 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348
Winson Chung0b560dd2014-01-21 13:00:26 -0800349 private boolean mNewDbCreated = false;
350
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100352 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800353 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700354 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700355
356 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
357 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700358 if (mMaxItemId == -1) {
359 mMaxItemId = initializeMaxItemId(getWritableDatabase());
360 }
361 if (mMaxScreenId == -1) {
362 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700363 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800364 }
365
Winson Chung0b560dd2014-01-21 13:00:26 -0800366 public boolean wasNewDbCreated() {
367 return mNewDbCreated;
368 }
369
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700370 /**
371 * Send notification that we've deleted the {@link AppWidgetHost},
372 * probably as part of the initial database creation. The receiver may
373 * want to re-call {@link AppWidgetHost#startListening()} to ensure
374 * callbacks are correctly set.
375 */
376 private void sendAppWidgetResetNotify() {
377 final ContentResolver resolver = mContext.getContentResolver();
378 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
379 }
380
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800381 @Override
382 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800383 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700384
Adam Cohendcd297f2013-06-18 13:13:40 -0700385 mMaxItemId = 1;
386 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800387 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700388
Kenny Guyed131872014-04-30 03:02:21 +0100389 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
390 long userSerialNumber = userManager.getSerialNumberForUser(
391 UserHandleCompat.myUserHandle());
392
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800393 db.execSQL("CREATE TABLE favorites (" +
394 "_id INTEGER PRIMARY KEY," +
395 "title TEXT," +
396 "intent TEXT," +
397 "container INTEGER," +
398 "screen INTEGER," +
399 "cellX INTEGER," +
400 "cellY INTEGER," +
401 "spanX INTEGER," +
402 "spanY INTEGER," +
403 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700404 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800405 "isShortcut INTEGER," +
406 "iconType INTEGER," +
407 "iconPackage TEXT," +
408 "iconResource TEXT," +
409 "icon BLOB," +
410 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400411 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400412 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500413 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100414 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800415 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
416 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800417 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700418 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800419
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700420 // Database was just created, so wipe any previous widgets
421 if (mAppWidgetHost != null) {
422 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700423 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800424 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700425
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800426 // Fresh and clean launcher DB.
427 mMaxItemId = initializeMaxItemId(db);
428 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800429 }
430
Adam Cohendcd297f2013-06-18 13:13:40 -0700431 private void addWorkspacesTable(SQLiteDatabase db) {
432 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800433 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400434 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
435 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700436 ");");
437 }
438
Adam Cohen119285e2014-04-02 16:59:08 -0700439 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700440 // Delete items directly on the workspace who's screen id doesn't exist
441 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
442 // AND container = -100"
443 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
444 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700445 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700446 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
447 " AND " +
448 LauncherSettings.Favorites.CONTAINER + " = " +
449 LauncherSettings.Favorites.CONTAINER_DESKTOP;
450 db.execSQL(removeOrphanedDesktopItems);
451
452 // Delete items contained in folders which no longer exist (after above statement)
453 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
454 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
455 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
456 " WHERE " +
457 LauncherSettings.Favorites.CONTAINER + " <> " +
458 LauncherSettings.Favorites.CONTAINER_DESKTOP +
459 " AND "
460 + LauncherSettings.Favorites.CONTAINER + " <> " +
461 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
462 " AND "
463 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
464 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
465 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
466 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
467 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700468 }
469
Winson Chungc763c4e2013-07-19 13:49:06 -0700470 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400471 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700472 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800473 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700474 }
475
Winson Chungc763c4e2013-07-19 13:49:06 -0700476 private void setFlagEmptyDbCreated() {
477 String spKey = LauncherAppState.getSharedPreferencesKey();
478 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800479 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700480 }
481
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800482 @Override
483 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700484 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800485 switch (oldVersion) {
486 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800487 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800488 case 12: {
489 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
490 // to persist workspace screens and their relative order.
491 mMaxScreenId = 0;
492 addWorkspacesTable(db);
493 }
494 case 13: {
495 db.beginTransaction();
496 try {
497 // Insert new column for holding widget provider name
498 db.execSQL("ALTER TABLE favorites " +
499 "ADD COLUMN appWidgetProvider TEXT;");
500 db.setTransactionSuccessful();
501 } catch (SQLException ex) {
502 Log.e(TAG, ex.getMessage(), ex);
503 // Old version remains, which means we wipe old data
504 break;
505 } finally {
506 db.endTransaction();
507 }
508 }
509 case 14: {
510 db.beginTransaction();
511 try {
512 // Insert new column for holding update timestamp
513 db.execSQL("ALTER TABLE favorites " +
514 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
515 db.execSQL("ALTER TABLE workspaceScreens " +
516 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
517 db.setTransactionSuccessful();
518 } catch (SQLException ex) {
519 Log.e(TAG, ex.getMessage(), ex);
520 // Old version remains, which means we wipe old data
521 break;
522 } finally {
523 db.endTransaction();
524 }
525 }
526 case 15: {
527 db.beginTransaction();
528 try {
529 // Insert new column for holding restore status
530 db.execSQL("ALTER TABLE favorites " +
531 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
532 db.setTransactionSuccessful();
533 } catch (SQLException ex) {
534 Log.e(TAG, ex.getMessage(), ex);
535 // Old version remains, which means we wipe old data
536 break;
537 } finally {
538 db.endTransaction();
539 }
540 }
541 case 16: {
542 // We use the db version upgrade here to identify users who may not have seen
543 // clings yet (because they weren't available), but for whom the clings are now
544 // available (tablet users). Because one of the possible cling flows (migration)
545 // is very destructive (wipes out workspaces), we want to prevent this from showing
546 // until clear data. We do so by marking that the clings have been shown.
547 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
548 }
549 case 17: {
550 // No-op
551 }
552 case 18: {
553 // Due to a data loss bug, some users may have items associated with screen ids
554 // which no longer exist. Since this can cause other problems, and since the user
555 // will never see these items anyway, we use database upgrade as an opportunity to
556 // clean things up.
557 removeOrphanedItems(db);
558 }
559 case 19: {
560 // Add userId column
561 if (!addProfileColumn(db)) {
562 // Old version remains, which means we wipe old data
563 break;
564 }
565 }
566 case 20:
567 if (!updateFolderItemsRank(db, true)) {
568 break;
569 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800570 case 21:
571 // Recreate workspace table with screen id a primary key
572 if (!recreateWorkspaceTable(db)) {
573 break;
574 }
575 case 22: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800576 // DB Upgraded successfully
577 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400578 }
579 }
580
Sunny Goyala2cc6242015-01-14 14:23:02 -0800581 // DB was not upgraded
582 Log.w(TAG, "Destroying all old data.");
583 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800585
Adam Cohen9b1d0622014-05-21 19:01:57 -0700586 @Override
587 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
588 // This shouldn't happen -- throw our hands up in the air and start over.
589 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
590 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700591 createEmptyDB(db);
592 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700593
Sunny Goyal42de82f2014-09-26 22:09:29 -0700594
595 /**
596 * Clears all the data for a fresh start.
597 */
598 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700599 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
600 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
601 onCreate(db);
602 }
603
Sunny Goyald2f38192015-02-25 10:46:34 -0800604 /**
605 * Recreates workspace table and migrates data to the new table.
606 */
607 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
608 db.beginTransaction();
609 try {
610 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
611 new String[] {LauncherSettings.WorkspaceScreens._ID},
612 null, null, null, null,
613 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
614 ArrayList<Long> sortedIDs = new ArrayList<Long>();
615 long maxId = 0;
616 try {
617 while (c.moveToNext()) {
618 Long id = c.getLong(0);
619 if (!sortedIDs.contains(id)) {
620 sortedIDs.add(id);
621 maxId = Math.max(maxId, id);
622 }
623 }
624 } finally {
625 c.close();
626 }
627
628 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
629 addWorkspacesTable(db);
630
631 // Add all screen ids back
632 int total = sortedIDs.size();
633 for (int i = 0; i < total; i++) {
634 ContentValues values = new ContentValues();
635 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
636 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
637 addModifiedTime(values);
638 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
639 }
640 db.setTransactionSuccessful();
641 mMaxScreenId = maxId;
642 } catch (SQLException ex) {
643 // Old version remains, which means we wipe old data
644 Log.e(TAG, ex.getMessage(), ex);
645 return false;
646 } finally {
647 db.endTransaction();
648 }
649 return true;
650 }
651
Sunny Goyal08f72612015-01-05 13:41:43 -0800652 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
653 db.beginTransaction();
654 try {
655 if (addRankColumn) {
656 // Insert new column for holding rank
657 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
658 }
659
660 // Get a map for folder ID to folder width
661 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
662 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
663 + " GROUP BY container;",
664 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
665
666 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800667 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
668 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800669 new Object[] {c.getLong(1) + 1, c.getLong(0)});
670 }
671
672 c.close();
673 db.setTransactionSuccessful();
674 } catch (SQLException ex) {
675 // Old version remains, which means we wipe old data
676 Log.e(TAG, ex.getMessage(), ex);
677 return false;
678 } finally {
679 db.endTransaction();
680 }
681 return true;
682 }
683
Kenny Guyed131872014-04-30 03:02:21 +0100684 private boolean addProfileColumn(SQLiteDatabase db) {
685 db.beginTransaction();
686 try {
687 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
688 // Default to the serial number of this user, for older
689 // shortcuts.
690 long userSerialNumber = userManager.getSerialNumberForUser(
691 UserHandleCompat.myUserHandle());
692 // Insert new column for holding user serial number
693 db.execSQL("ALTER TABLE favorites " +
694 "ADD COLUMN profileId INTEGER DEFAULT "
695 + userSerialNumber + ";");
696 db.setTransactionSuccessful();
697 } catch (SQLException ex) {
698 // Old version remains, which means we wipe old data
699 Log.e(TAG, ex.getMessage(), ex);
700 return false;
701 } finally {
702 db.endTransaction();
703 }
704 return true;
705 }
706
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700707 // Generates a new ID to use for an object in your database. This method should be only
708 // called from the main UI thread. As an exception, we do call it when we call the
709 // constructor from the worker thread; however, this doesn't extend until after the
710 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
711 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700712 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 public long generateNewItemId() {
714 if (mMaxItemId < 0) {
715 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700716 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700717 mMaxItemId += 1;
718 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700719 }
720
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700721 @Override
722 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
723 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
724 }
725
Winson Chungc763c4e2013-07-19 13:49:06 -0700726 public void updateMaxItemId(long id) {
727 mMaxItemId = id + 1;
728 }
729
Chris Wren5dee7af2013-12-20 17:22:11 -0500730 public void checkId(String table, ContentValues values) {
731 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
732 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
733 mMaxScreenId = Math.max(id, mMaxScreenId);
734 } else {
735 mMaxItemId = Math.max(id, mMaxItemId);
736 }
737 }
738
Adam Cohendcd297f2013-06-18 13:13:40 -0700739 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800740 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700741 }
742
743 // Generates a new ID to use for an workspace screen in your database. This method
744 // should be only called from the main UI thread. As an exception, we do call it when we
745 // call the constructor from the worker thread; however, this doesn't extend until after the
746 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
747 // after that point
748 public long generateNewScreenId() {
749 if (mMaxScreenId < 0) {
750 throw new RuntimeException("Error: max screen id was not initialized");
751 }
752 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800753 // Log to disk
754 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700755 return mMaxScreenId;
756 }
757
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800759 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800760 }
761
Adam Cohena043fa82014-07-23 14:49:38 -0700762 private boolean initializeExternalAdd(ContentValues values) {
763 // 1. Ensure that externally added items have a valid item id
764 long id = generateNewItemId();
765 values.put(LauncherSettings.Favorites._ID, id);
766
767 // 2. In the case of an app widget, and if no app widget id is specified, we
768 // attempt allocate and bind the widget.
769 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
770 if (itemType != null &&
771 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
772 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
773
774 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
775 ComponentName cn = ComponentName.unflattenFromString(
776 values.getAsString(Favorites.APPWIDGET_PROVIDER));
777
778 if (cn != null) {
779 try {
780 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700781 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700782 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700783 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700784 }
785 } catch (RuntimeException e) {
786 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700787 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700788 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700789 } else {
790 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700791 }
792 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700793
794 // Add screen id if not present
795 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
796 if (!addScreenIdIfNecessary(screenId)) {
797 return false;
798 }
Adam Cohena043fa82014-07-23 14:49:38 -0700799 return true;
800 }
801
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700802 // Returns true of screen id exists, or if successfully added
803 private boolean addScreenIdIfNecessary(long screenId) {
804 if (!hasScreenId(screenId)) {
805 int rank = getMaxScreenRank() + 1;
806
807 ContentValues v = new ContentValues();
808 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
809 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
810 if (dbInsertAndCheck(this, getWritableDatabase(),
811 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
812 return false;
813 }
814 }
815 return true;
816 }
817
818 private boolean hasScreenId(long screenId) {
819 SQLiteDatabase db = getWritableDatabase();
820 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
821 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
822 if (c != null) {
823 int count = c.getCount();
824 c.close();
825 return count > 0;
826 } else {
827 return false;
828 }
829 }
830
831 private int getMaxScreenRank() {
832 SQLiteDatabase db = getWritableDatabase();
833 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
834 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
835
836 // get the result
837 final int maxRankIndex = 0;
838 int rank = -1;
839 if (c != null && c.moveToNext()) {
840 rank = c.getInt(maxRankIndex);
841 }
842 if (c != null) {
843 c.close();
844 }
845
846 return rank;
847 }
848
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700849 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700850 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700851 // TODO: Use multiple loaders with fall-back and transaction.
852 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700853
854 // Add the screens specified by the items above
855 Collections.sort(screenIds);
856 int rank = 0;
857 ContentValues values = new ContentValues();
858 for (Long id : screenIds) {
859 values.clear();
860 values.put(LauncherSettings.WorkspaceScreens._ID, id);
861 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
862 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
863 throw new RuntimeException("Failed initialize screen table"
864 + "from default layout");
865 }
866 rank++;
867 }
868
869 // Ensure that the max ids are initialized
870 mMaxItemId = initializeMaxItemId(db);
871 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700872
Adam Cohen71483f42014-05-15 14:04:01 -0700873 return count;
874 }
875
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700876 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500877 final ContentResolver resolver = mContext.getContentResolver();
878 Cursor c = null;
879 int count = 0;
880 int curScreen = 0;
881
882 try {
883 c = resolver.query(uri, null, null, null, "title ASC");
884 } catch (Exception e) {
885 // Ignore
886 }
887
Dan Sandlerd5024042014-01-09 15:01:33 -0500888 // We already have a favorites database in the old provider
889 if (c != null) {
890 try {
891 if (c.getCount() > 0) {
892 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
893 final int intentIndex
894 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
895 final int titleIndex
896 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
897 final int iconTypeIndex
898 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
899 final int iconIndex
900 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
901 final int iconPackageIndex
902 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
903 final int iconResourceIndex
904 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
905 final int containerIndex
906 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
907 final int itemTypeIndex
908 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
909 final int screenIndex
910 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
911 final int cellXIndex
912 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
913 final int cellYIndex
914 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
915 final int uriIndex
916 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
917 final int displayModeIndex
918 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100919 final int profileIndex
920 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500921
922 int i = 0;
923 int curX = 0;
924 int curY = 0;
925
926 final LauncherAppState app = LauncherAppState.getInstance();
927 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
928 final int width = (int) grid.numColumns;
929 final int height = (int) grid.numRows;
930 final int hotseatWidth = (int) grid.numHotseatIcons;
931
932 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
933
Adam Cohen72960972014-01-15 18:13:55 -0800934 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
935 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500936 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500937
938 while (c.moveToNext()) {
939 final int itemType = c.getInt(itemTypeIndex);
940 if (itemType != Favorites.ITEM_TYPE_APPLICATION
941 && itemType != Favorites.ITEM_TYPE_SHORTCUT
942 && itemType != Favorites.ITEM_TYPE_FOLDER) {
943 continue;
944 }
945
946 final int cellX = c.getInt(cellXIndex);
947 final int cellY = c.getInt(cellYIndex);
948 final int screen = c.getInt(screenIndex);
949 int container = c.getInt(containerIndex);
950 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100951
952 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
953 UserHandleCompat userHandle;
954 final long userSerialNumber;
955 if (profileIndex != -1 && !c.isNull(profileIndex)) {
956 userSerialNumber = c.getInt(profileIndex);
957 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
958 } else {
959 // Default to the serial number of this user, for older
960 // shortcuts.
961 userHandle = UserHandleCompat.myUserHandle();
962 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
963 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800964
965 if (userHandle == null) {
966 Launcher.addDumpLog(TAG, "skipping deleted user", true);
967 continue;
968 }
969
Dan Sandlerd5024042014-01-09 15:01:33 -0500970 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500971 + c.getString(titleIndex) + "\" ("
972 + cellX + "," + cellY + "@"
973 + LauncherSettings.Favorites.containerToString(container)
974 + "/" + screen
975 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500976
977 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800978
979 final Intent intent;
980 final ComponentName cn;
981 try {
982 intent = Intent.parseUri(intentStr, 0);
983 } catch (URISyntaxException e) {
984 // bogus intent?
985 Launcher.addDumpLog(TAG,
986 "skipping invalid intent uri", true);
987 continue;
988 }
989
990 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500991 if (TextUtils.isEmpty(intentStr)) {
992 // no intent? no icon
993 Launcher.addDumpLog(TAG, "skipping empty intent", true);
994 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800995 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100996 !LauncherModel.isValidPackageActivity(mContext, cn,
997 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800998 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800999 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001000 "no longer exists.", true);
1001 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001002 } else if (container ==
1003 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1004 // Dedupe icons directly on the workspace
1005
Adam Cohen556f6132014-01-15 15:18:08 -08001006 // Canonicalize
1007 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001008 // does not, so we clear that out to keep them the same.
1009 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001010 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001011 int flags = intent.getFlags();
1012 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001013 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001014 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001015 if (seenIntents.contains(key)) {
1016 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001017 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001018 } else {
1019 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001020 }
1021 }
1022 }
1023
1024 ContentValues values = new ContentValues(c.getColumnCount());
1025 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1026 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1027 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1028 values.put(LauncherSettings.Favorites.ICON_TYPE,
1029 c.getInt(iconTypeIndex));
1030 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1031 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1032 c.getString(iconPackageIndex));
1033 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1034 c.getString(iconResourceIndex));
1035 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1036 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1037 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1038 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1039 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001040 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001041
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001042 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1043 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001044 }
1045
1046 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1047 // In a folder or in the hotseat, preserve position
1048 values.put(LauncherSettings.Favorites.SCREEN, screen);
1049 values.put(LauncherSettings.Favorites.CELLX, cellX);
1050 values.put(LauncherSettings.Favorites.CELLY, cellY);
1051 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001052 // For items contained directly on one of the workspace screen,
1053 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001054 }
1055
1056 values.put(LauncherSettings.Favorites.CONTAINER, container);
1057
Adam Cohen72960972014-01-15 18:13:55 -08001058 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1059 shortcuts.add(values);
1060 } else {
1061 folders.add(values);
1062 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001063 }
1064
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001065 // Now that we have all the hotseat icons, let's go through them left-right
1066 // and assign valid locations for them in the new hotseat
1067 final int N = hotseat.size();
1068 for (int idx=0; idx<N; idx++) {
1069 int hotseatX = hotseat.keyAt(idx);
1070 ContentValues values = hotseat.valueAt(idx);
1071
1072 if (hotseatX == grid.hotseatAllAppsRank) {
1073 // let's drop this in the next available hole in the hotseat
1074 while (++hotseatX < hotseatWidth) {
1075 if (hotseat.get(hotseatX) == null) {
1076 // found a spot! move it here
1077 values.put(LauncherSettings.Favorites.SCREEN,
1078 hotseatX);
1079 break;
1080 }
1081 }
1082 }
1083 if (hotseatX >= hotseatWidth) {
1084 // no room for you in the hotseat? it's off to the desktop with you
1085 values.put(LauncherSettings.Favorites.CONTAINER,
1086 Favorites.CONTAINER_DESKTOP);
1087 }
1088 }
1089
Adam Cohen72960972014-01-15 18:13:55 -08001090 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1091 // Folders first
1092 allItems.addAll(folders);
1093 // Then shortcuts
1094 allItems.addAll(shortcuts);
1095
1096 // Layout all the folders
1097 for (ContentValues values: allItems) {
1098 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1099 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1100 // Hotseat items and folder items have already had their
1101 // location information set. Nothing to be done here.
1102 continue;
1103 }
1104 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1105 values.put(LauncherSettings.Favorites.CELLX, curX);
1106 values.put(LauncherSettings.Favorites.CELLY, curY);
1107 curX = (curX + 1) % width;
1108 if (curX == 0) {
1109 curY = (curY + 1);
1110 }
1111 // Leave the last row of icons blank on every screen
1112 if (curY == height - 1) {
1113 curScreen = (int) generateNewScreenId();
1114 curY = 0;
1115 }
1116 }
1117
1118 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001119 db.beginTransaction();
1120 try {
Adam Cohen72960972014-01-15 18:13:55 -08001121 for (ContentValues row: allItems) {
1122 if (row == null) continue;
1123 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001124 < 0) {
1125 return;
1126 } else {
1127 count++;
1128 }
1129 }
1130 db.setTransactionSuccessful();
1131 } finally {
1132 db.endTransaction();
1133 }
1134 }
1135
1136 db.beginTransaction();
1137 try {
1138 for (i=0; i<=curScreen; i++) {
1139 final ContentValues values = new ContentValues();
1140 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1141 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1142 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1143 < 0) {
1144 return;
1145 }
1146 }
1147 db.setTransactionSuccessful();
1148 } finally {
1149 db.endTransaction();
1150 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001151
1152 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001153 }
1154 } finally {
1155 c.close();
1156 }
1157 }
1158
1159 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1160 + (curScreen+1) + " screens", true);
1161
1162 // ensure that new screens are created to hold these icons
1163 setFlagJustLoadedOldDb();
1164
1165 // Update max IDs; very important since we just grabbed IDs from another database
1166 mMaxItemId = initializeMaxItemId(db);
1167 mMaxScreenId = initializeMaxScreenId(db);
1168 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1169 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001170 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001171
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001172 /**
1173 * @return the max _id in the provided table.
1174 */
1175 private static long getMaxId(SQLiteDatabase db, String table) {
1176 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1177 // get the result
1178 long id = -1;
1179 if (c != null && c.moveToNext()) {
1180 id = c.getLong(0);
1181 }
1182 if (c != null) {
1183 c.close();
1184 }
1185
1186 if (id == -1) {
1187 throw new RuntimeException("Error: could not query max id in " + table);
1188 }
1189
1190 return id;
1191 }
1192
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 static class SqlArguments {
1194 public final String table;
1195 public final String where;
1196 public final String[] args;
1197
1198 SqlArguments(Uri url, String where, String[] args) {
1199 if (url.getPathSegments().size() == 1) {
1200 this.table = url.getPathSegments().get(0);
1201 this.where = where;
1202 this.args = args;
1203 } else if (url.getPathSegments().size() != 2) {
1204 throw new IllegalArgumentException("Invalid URI: " + url);
1205 } else if (!TextUtils.isEmpty(where)) {
1206 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1207 } else {
1208 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001209 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001210 this.args = null;
1211 }
1212 }
1213
1214 SqlArguments(Uri url) {
1215 if (url.getPathSegments().size() == 1) {
1216 table = url.getPathSegments().get(0);
1217 where = null;
1218 args = null;
1219 } else {
1220 throw new IllegalArgumentException("Invalid URI: " + url);
1221 }
1222 }
1223 }
Adam Cohen72960972014-01-15 18:13:55 -08001224}