blob: 59c8d929a4f15a5b7d9a2aaf3d977c0d376dde88 [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 Goyal5d85c442015-03-10 13:14:47 -070060 private static final int DATABASE_VERSION = 23;
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 + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700416 "rank INTEGER NOT NULL DEFAULT 0," +
417 "options 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 + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800434 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
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);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800474 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700475 }
476
Winson Chungc763c4e2013-07-19 13:49:06 -0700477 private void setFlagEmptyDbCreated() {
478 String spKey = LauncherAppState.getSharedPreferencesKey();
479 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800480 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700481 }
482
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800483 @Override
484 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700485 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800486 switch (oldVersion) {
487 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800488 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800489 case 12: {
490 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
491 // to persist workspace screens and their relative order.
492 mMaxScreenId = 0;
493 addWorkspacesTable(db);
494 }
495 case 13: {
496 db.beginTransaction();
497 try {
498 // Insert new column for holding widget provider name
499 db.execSQL("ALTER TABLE favorites " +
500 "ADD COLUMN appWidgetProvider TEXT;");
501 db.setTransactionSuccessful();
502 } catch (SQLException ex) {
503 Log.e(TAG, ex.getMessage(), ex);
504 // Old version remains, which means we wipe old data
505 break;
506 } finally {
507 db.endTransaction();
508 }
509 }
510 case 14: {
511 db.beginTransaction();
512 try {
513 // Insert new column for holding update timestamp
514 db.execSQL("ALTER TABLE favorites " +
515 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
516 db.execSQL("ALTER TABLE workspaceScreens " +
517 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
518 db.setTransactionSuccessful();
519 } catch (SQLException ex) {
520 Log.e(TAG, ex.getMessage(), ex);
521 // Old version remains, which means we wipe old data
522 break;
523 } finally {
524 db.endTransaction();
525 }
526 }
527 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700528 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800529 // Old version remains, which means we wipe old data
530 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800531 }
532 }
533 case 16: {
534 // We use the db version upgrade here to identify users who may not have seen
535 // clings yet (because they weren't available), but for whom the clings are now
536 // available (tablet users). Because one of the possible cling flows (migration)
537 // is very destructive (wipes out workspaces), we want to prevent this from showing
538 // until clear data. We do so by marking that the clings have been shown.
539 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
540 }
541 case 17: {
542 // No-op
543 }
544 case 18: {
545 // Due to a data loss bug, some users may have items associated with screen ids
546 // which no longer exist. Since this can cause other problems, and since the user
547 // will never see these items anyway, we use database upgrade as an opportunity to
548 // clean things up.
549 removeOrphanedItems(db);
550 }
551 case 19: {
552 // Add userId column
553 if (!addProfileColumn(db)) {
554 // Old version remains, which means we wipe old data
555 break;
556 }
557 }
558 case 20:
559 if (!updateFolderItemsRank(db, true)) {
560 break;
561 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800562 case 21:
563 // Recreate workspace table with screen id a primary key
564 if (!recreateWorkspaceTable(db)) {
565 break;
566 }
567 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700568 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
569 // Old version remains, which means we wipe old data
570 break;
571 }
572 }
573 case 23: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800574 // DB Upgraded successfully
575 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400576 }
577 }
578
Sunny Goyala2cc6242015-01-14 14:23:02 -0800579 // DB was not upgraded
580 Log.w(TAG, "Destroying all old data.");
581 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800583
Adam Cohen9b1d0622014-05-21 19:01:57 -0700584 @Override
585 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
586 // This shouldn't happen -- throw our hands up in the air and start over.
587 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
588 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700589 createEmptyDB(db);
590 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700591
Sunny Goyal42de82f2014-09-26 22:09:29 -0700592
593 /**
594 * Clears all the data for a fresh start.
595 */
596 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700597 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
598 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
599 onCreate(db);
600 }
601
Sunny Goyald2f38192015-02-25 10:46:34 -0800602 /**
603 * Recreates workspace table and migrates data to the new table.
604 */
605 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
606 db.beginTransaction();
607 try {
608 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
609 new String[] {LauncherSettings.WorkspaceScreens._ID},
610 null, null, null, null,
611 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
612 ArrayList<Long> sortedIDs = new ArrayList<Long>();
613 long maxId = 0;
614 try {
615 while (c.moveToNext()) {
616 Long id = c.getLong(0);
617 if (!sortedIDs.contains(id)) {
618 sortedIDs.add(id);
619 maxId = Math.max(maxId, id);
620 }
621 }
622 } finally {
623 c.close();
624 }
625
626 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
627 addWorkspacesTable(db);
628
629 // Add all screen ids back
630 int total = sortedIDs.size();
631 for (int i = 0; i < total; i++) {
632 ContentValues values = new ContentValues();
633 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
634 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
635 addModifiedTime(values);
636 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
637 }
638 db.setTransactionSuccessful();
639 mMaxScreenId = maxId;
640 } catch (SQLException ex) {
641 // Old version remains, which means we wipe old data
642 Log.e(TAG, ex.getMessage(), ex);
643 return false;
644 } finally {
645 db.endTransaction();
646 }
647 return true;
648 }
649
Sunny Goyal08f72612015-01-05 13:41:43 -0800650 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
651 db.beginTransaction();
652 try {
653 if (addRankColumn) {
654 // Insert new column for holding rank
655 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
656 }
657
658 // Get a map for folder ID to folder width
659 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
660 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
661 + " GROUP BY container;",
662 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
663
664 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800665 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
666 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800667 new Object[] {c.getLong(1) + 1, c.getLong(0)});
668 }
669
670 c.close();
671 db.setTransactionSuccessful();
672 } catch (SQLException ex) {
673 // Old version remains, which means we wipe old data
674 Log.e(TAG, ex.getMessage(), ex);
675 return false;
676 } finally {
677 db.endTransaction();
678 }
679 return true;
680 }
681
Kenny Guyed131872014-04-30 03:02:21 +0100682 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700683 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
684 // Default to the serial number of this user, for older
685 // shortcuts.
686 long userSerialNumber = userManager.getSerialNumberForUser(
687 UserHandleCompat.myUserHandle());
688 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
689 }
690
691 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100692 db.beginTransaction();
693 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700694 db.execSQL("ALTER TABLE favorites ADD COLUMN "
695 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100696 db.setTransactionSuccessful();
697 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100698 Log.e(TAG, ex.getMessage(), ex);
699 return false;
700 } finally {
701 db.endTransaction();
702 }
703 return true;
704 }
705
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700706 // Generates a new ID to use for an object in your database. This method should be only
707 // called from the main UI thread. As an exception, we do call it when we call the
708 // constructor from the worker thread; however, this doesn't extend until after the
709 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
710 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700711 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700712 public long generateNewItemId() {
713 if (mMaxItemId < 0) {
714 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700715 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700716 mMaxItemId += 1;
717 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700718 }
719
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700720 @Override
721 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
722 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
723 }
724
Winson Chungc763c4e2013-07-19 13:49:06 -0700725 public void updateMaxItemId(long id) {
726 mMaxItemId = id + 1;
727 }
728
Chris Wren5dee7af2013-12-20 17:22:11 -0500729 public void checkId(String table, ContentValues values) {
730 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
731 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
732 mMaxScreenId = Math.max(id, mMaxScreenId);
733 } else {
734 mMaxItemId = Math.max(id, mMaxItemId);
735 }
736 }
737
Adam Cohendcd297f2013-06-18 13:13:40 -0700738 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800739 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700740 }
741
742 // Generates a new ID to use for an workspace screen in your database. This method
743 // should be only called from the main UI thread. As an exception, we do call it when we
744 // call the constructor from the worker thread; however, this doesn't extend until after the
745 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
746 // after that point
747 public long generateNewScreenId() {
748 if (mMaxScreenId < 0) {
749 throw new RuntimeException("Error: max screen id was not initialized");
750 }
751 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800752 // Log to disk
753 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700754 return mMaxScreenId;
755 }
756
Adam Cohendcd297f2013-06-18 13:13:40 -0700757 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800758 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800759 }
760
Adam Cohena043fa82014-07-23 14:49:38 -0700761 private boolean initializeExternalAdd(ContentValues values) {
762 // 1. Ensure that externally added items have a valid item id
763 long id = generateNewItemId();
764 values.put(LauncherSettings.Favorites._ID, id);
765
766 // 2. In the case of an app widget, and if no app widget id is specified, we
767 // attempt allocate and bind the widget.
768 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
769 if (itemType != null &&
770 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
771 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
772
773 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
774 ComponentName cn = ComponentName.unflattenFromString(
775 values.getAsString(Favorites.APPWIDGET_PROVIDER));
776
777 if (cn != null) {
778 try {
779 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700780 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700781 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700782 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700783 }
784 } catch (RuntimeException e) {
785 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700786 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700787 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700788 } else {
789 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700790 }
791 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700792
793 // Add screen id if not present
794 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
795 if (!addScreenIdIfNecessary(screenId)) {
796 return false;
797 }
Adam Cohena043fa82014-07-23 14:49:38 -0700798 return true;
799 }
800
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700801 // Returns true of screen id exists, or if successfully added
802 private boolean addScreenIdIfNecessary(long screenId) {
803 if (!hasScreenId(screenId)) {
804 int rank = getMaxScreenRank() + 1;
805
806 ContentValues v = new ContentValues();
807 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
808 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
809 if (dbInsertAndCheck(this, getWritableDatabase(),
810 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
811 return false;
812 }
813 }
814 return true;
815 }
816
817 private boolean hasScreenId(long screenId) {
818 SQLiteDatabase db = getWritableDatabase();
819 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
820 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
821 if (c != null) {
822 int count = c.getCount();
823 c.close();
824 return count > 0;
825 } else {
826 return false;
827 }
828 }
829
830 private int getMaxScreenRank() {
831 SQLiteDatabase db = getWritableDatabase();
832 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
833 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
834
835 // get the result
836 final int maxRankIndex = 0;
837 int rank = -1;
838 if (c != null && c.moveToNext()) {
839 rank = c.getInt(maxRankIndex);
840 }
841 if (c != null) {
842 c.close();
843 }
844
845 return rank;
846 }
847
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700848 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700849 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700850 // TODO: Use multiple loaders with fall-back and transaction.
851 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700852
853 // Add the screens specified by the items above
854 Collections.sort(screenIds);
855 int rank = 0;
856 ContentValues values = new ContentValues();
857 for (Long id : screenIds) {
858 values.clear();
859 values.put(LauncherSettings.WorkspaceScreens._ID, id);
860 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
861 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
862 throw new RuntimeException("Failed initialize screen table"
863 + "from default layout");
864 }
865 rank++;
866 }
867
868 // Ensure that the max ids are initialized
869 mMaxItemId = initializeMaxItemId(db);
870 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700871
Adam Cohen71483f42014-05-15 14:04:01 -0700872 return count;
873 }
874
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700875 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500876 final ContentResolver resolver = mContext.getContentResolver();
877 Cursor c = null;
878 int count = 0;
879 int curScreen = 0;
880
881 try {
882 c = resolver.query(uri, null, null, null, "title ASC");
883 } catch (Exception e) {
884 // Ignore
885 }
886
Dan Sandlerd5024042014-01-09 15:01:33 -0500887 // We already have a favorites database in the old provider
888 if (c != null) {
889 try {
890 if (c.getCount() > 0) {
891 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
892 final int intentIndex
893 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
894 final int titleIndex
895 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
896 final int iconTypeIndex
897 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
898 final int iconIndex
899 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
900 final int iconPackageIndex
901 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
902 final int iconResourceIndex
903 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
904 final int containerIndex
905 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
906 final int itemTypeIndex
907 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
908 final int screenIndex
909 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
910 final int cellXIndex
911 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
912 final int cellYIndex
913 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
914 final int uriIndex
915 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
916 final int displayModeIndex
917 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100918 final int profileIndex
919 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500920
921 int i = 0;
922 int curX = 0;
923 int curY = 0;
924
925 final LauncherAppState app = LauncherAppState.getInstance();
926 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
927 final int width = (int) grid.numColumns;
928 final int height = (int) grid.numRows;
929 final int hotseatWidth = (int) grid.numHotseatIcons;
930
931 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
932
Adam Cohen72960972014-01-15 18:13:55 -0800933 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
934 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500935 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500936
937 while (c.moveToNext()) {
938 final int itemType = c.getInt(itemTypeIndex);
939 if (itemType != Favorites.ITEM_TYPE_APPLICATION
940 && itemType != Favorites.ITEM_TYPE_SHORTCUT
941 && itemType != Favorites.ITEM_TYPE_FOLDER) {
942 continue;
943 }
944
945 final int cellX = c.getInt(cellXIndex);
946 final int cellY = c.getInt(cellYIndex);
947 final int screen = c.getInt(screenIndex);
948 int container = c.getInt(containerIndex);
949 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100950
951 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
952 UserHandleCompat userHandle;
953 final long userSerialNumber;
954 if (profileIndex != -1 && !c.isNull(profileIndex)) {
955 userSerialNumber = c.getInt(profileIndex);
956 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
957 } else {
958 // Default to the serial number of this user, for older
959 // shortcuts.
960 userHandle = UserHandleCompat.myUserHandle();
961 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
962 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800963
964 if (userHandle == null) {
965 Launcher.addDumpLog(TAG, "skipping deleted user", true);
966 continue;
967 }
968
Dan Sandlerd5024042014-01-09 15:01:33 -0500969 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500970 + c.getString(titleIndex) + "\" ("
971 + cellX + "," + cellY + "@"
972 + LauncherSettings.Favorites.containerToString(container)
973 + "/" + screen
974 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500975
976 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800977
978 final Intent intent;
979 final ComponentName cn;
980 try {
981 intent = Intent.parseUri(intentStr, 0);
982 } catch (URISyntaxException e) {
983 // bogus intent?
984 Launcher.addDumpLog(TAG,
985 "skipping invalid intent uri", true);
986 continue;
987 }
988
989 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500990 if (TextUtils.isEmpty(intentStr)) {
991 // no intent? no icon
992 Launcher.addDumpLog(TAG, "skipping empty intent", true);
993 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800994 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100995 !LauncherModel.isValidPackageActivity(mContext, cn,
996 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800997 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800998 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -0800999 "no longer exists.", true);
1000 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001001 } else if (container ==
1002 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1003 // Dedupe icons directly on the workspace
1004
Adam Cohen556f6132014-01-15 15:18:08 -08001005 // Canonicalize
1006 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001007 // does not, so we clear that out to keep them the same.
1008 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001009 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001010 int flags = intent.getFlags();
1011 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001012 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001013 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001014 if (seenIntents.contains(key)) {
1015 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001016 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001017 } else {
1018 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001019 }
1020 }
1021 }
1022
1023 ContentValues values = new ContentValues(c.getColumnCount());
1024 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1025 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1026 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1027 values.put(LauncherSettings.Favorites.ICON_TYPE,
1028 c.getInt(iconTypeIndex));
1029 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1030 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1031 c.getString(iconPackageIndex));
1032 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1033 c.getString(iconResourceIndex));
1034 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1035 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1036 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1037 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1038 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001039 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001040
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001041 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1042 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001043 }
1044
1045 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1046 // In a folder or in the hotseat, preserve position
1047 values.put(LauncherSettings.Favorites.SCREEN, screen);
1048 values.put(LauncherSettings.Favorites.CELLX, cellX);
1049 values.put(LauncherSettings.Favorites.CELLY, cellY);
1050 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001051 // For items contained directly on one of the workspace screen,
1052 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001053 }
1054
1055 values.put(LauncherSettings.Favorites.CONTAINER, container);
1056
Adam Cohen72960972014-01-15 18:13:55 -08001057 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1058 shortcuts.add(values);
1059 } else {
1060 folders.add(values);
1061 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001062 }
1063
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001064 // Now that we have all the hotseat icons, let's go through them left-right
1065 // and assign valid locations for them in the new hotseat
1066 final int N = hotseat.size();
1067 for (int idx=0; idx<N; idx++) {
1068 int hotseatX = hotseat.keyAt(idx);
1069 ContentValues values = hotseat.valueAt(idx);
1070
1071 if (hotseatX == grid.hotseatAllAppsRank) {
1072 // let's drop this in the next available hole in the hotseat
1073 while (++hotseatX < hotseatWidth) {
1074 if (hotseat.get(hotseatX) == null) {
1075 // found a spot! move it here
1076 values.put(LauncherSettings.Favorites.SCREEN,
1077 hotseatX);
1078 break;
1079 }
1080 }
1081 }
1082 if (hotseatX >= hotseatWidth) {
1083 // no room for you in the hotseat? it's off to the desktop with you
1084 values.put(LauncherSettings.Favorites.CONTAINER,
1085 Favorites.CONTAINER_DESKTOP);
1086 }
1087 }
1088
Adam Cohen72960972014-01-15 18:13:55 -08001089 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1090 // Folders first
1091 allItems.addAll(folders);
1092 // Then shortcuts
1093 allItems.addAll(shortcuts);
1094
1095 // Layout all the folders
1096 for (ContentValues values: allItems) {
1097 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1098 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1099 // Hotseat items and folder items have already had their
1100 // location information set. Nothing to be done here.
1101 continue;
1102 }
1103 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1104 values.put(LauncherSettings.Favorites.CELLX, curX);
1105 values.put(LauncherSettings.Favorites.CELLY, curY);
1106 curX = (curX + 1) % width;
1107 if (curX == 0) {
1108 curY = (curY + 1);
1109 }
1110 // Leave the last row of icons blank on every screen
1111 if (curY == height - 1) {
1112 curScreen = (int) generateNewScreenId();
1113 curY = 0;
1114 }
1115 }
1116
1117 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001118 db.beginTransaction();
1119 try {
Adam Cohen72960972014-01-15 18:13:55 -08001120 for (ContentValues row: allItems) {
1121 if (row == null) continue;
1122 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001123 < 0) {
1124 return;
1125 } else {
1126 count++;
1127 }
1128 }
1129 db.setTransactionSuccessful();
1130 } finally {
1131 db.endTransaction();
1132 }
1133 }
1134
1135 db.beginTransaction();
1136 try {
1137 for (i=0; i<=curScreen; i++) {
1138 final ContentValues values = new ContentValues();
1139 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1140 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1141 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1142 < 0) {
1143 return;
1144 }
1145 }
1146 db.setTransactionSuccessful();
1147 } finally {
1148 db.endTransaction();
1149 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001150
1151 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001152 }
1153 } finally {
1154 c.close();
1155 }
1156 }
1157
1158 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1159 + (curScreen+1) + " screens", true);
1160
1161 // ensure that new screens are created to hold these icons
1162 setFlagJustLoadedOldDb();
1163
1164 // Update max IDs; very important since we just grabbed IDs from another database
1165 mMaxItemId = initializeMaxItemId(db);
1166 mMaxScreenId = initializeMaxScreenId(db);
1167 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1168 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001169 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001170
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001171 /**
1172 * @return the max _id in the provided table.
1173 */
1174 private static long getMaxId(SQLiteDatabase db, String table) {
1175 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1176 // get the result
1177 long id = -1;
1178 if (c != null && c.moveToNext()) {
1179 id = c.getLong(0);
1180 }
1181 if (c != null) {
1182 c.close();
1183 }
1184
1185 if (id == -1) {
1186 throw new RuntimeException("Error: could not query max id in " + table);
1187 }
1188
1189 return id;
1190 }
1191
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001192 static class SqlArguments {
1193 public final String table;
1194 public final String where;
1195 public final String[] args;
1196
1197 SqlArguments(Uri url, String where, String[] args) {
1198 if (url.getPathSegments().size() == 1) {
1199 this.table = url.getPathSegments().get(0);
1200 this.where = where;
1201 this.args = args;
1202 } else if (url.getPathSegments().size() != 2) {
1203 throw new IllegalArgumentException("Invalid URI: " + url);
1204 } else if (!TextUtils.isEmpty(where)) {
1205 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1206 } else {
1207 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001208 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001209 this.args = null;
1210 }
1211 }
1212
1213 SqlArguments(Uri url) {
1214 if (url.getPathSegments().size() == 1) {
1215 table = url.getPathSegments().get(0);
1216 where = null;
1217 args = null;
1218 } else {
1219 throw new IllegalArgumentException("Invalid URI: " + url);
1220 }
1221 }
1222 }
Adam Cohen72960972014-01-15 18:13:55 -08001223}