blob: 0cdd64c2aed93567a0ffd2996bd1d88327635c29 [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);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800154 if (rowId <= 0) return null;
155
156 uri = ContentUris.withAppendedId(uri, rowId);
157 sendNotify(uri);
158
159 return uri;
160 }
161
Adam Cohena043fa82014-07-23 14:49:38 -0700162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public int bulkInsert(Uri uri, ContentValues[] values) {
165 SqlArguments args = new SqlArguments(uri);
166
167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
168 db.beginTransaction();
169 try {
170 int numValues = values.length;
171 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400172 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
174 return 0;
175 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176 }
177 db.setTransactionSuccessful();
178 } finally {
179 db.endTransaction();
180 }
181
182 sendNotify(uri);
183 return values.length;
184 }
185
186 @Override
Yura085c8532014-02-11 15:15:29 +0000187 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
188 throws OperationApplicationException {
189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
190 db.beginTransaction();
191 try {
192 ContentProviderResult[] result = super.applyBatch(operations);
193 db.setTransactionSuccessful();
194 return result;
195 } finally {
196 db.endTransaction();
197 }
198 }
199
200 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 public int delete(Uri uri, String selection, String[] selectionArgs) {
202 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
203
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 int count = db.delete(args.table, args.where, args.args);
206 if (count > 0) sendNotify(uri);
207
208 return count;
209 }
210
211 @Override
212 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
213 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
214
Chris Wren1ada10d2013-09-13 18:01:38 -0400215 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
217 int count = db.update(args.table, values, args.where, args.args);
218 if (count > 0) sendNotify(uri);
219
220 return count;
221 }
222
223 private void sendNotify(Uri uri) {
224 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
225 if (notify == null || "true".equals(notify)) {
226 getContext().getContentResolver().notifyChange(uri, null);
227 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400228
229 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400230 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700231 if (mListener != null) {
232 mListener.onLauncherProviderChange();
233 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400234 }
235
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 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700300 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700301 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
302 && usingExternallyProvidedLayout) {
303 // Unable to load external layout. Cleanup and load the internal layout.
304 createEmptyDB();
305 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
306 getDefaultLayoutParser());
307 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700308 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700309 }
310 }
311
Sunny Goyal9d219682014-10-23 14:21:02 -0700312 private DefaultLayoutParser getDefaultLayoutParser() {
313 int defaultLayout = LauncherAppState.getInstance()
314 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
315 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
316 mOpenHelper, getContext().getResources(), defaultLayout);
317 }
318
Dan Sandlerd5024042014-01-09 15:01:33 -0500319 public void migrateLauncher2Shortcuts() {
320 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400321 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500322 }
323
Sunny Goyal08f72612015-01-05 13:41:43 -0800324 public void updateFolderItemsRank() {
325 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
326 }
327
Dan Sandlerd5024042014-01-09 15:01:33 -0500328 public void deleteDatabase() {
329 // Are you sure? (y/n)
330 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500331 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500332 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500333 if (dbFile.exists()) {
334 SQLiteDatabase.deleteDatabase(dbFile);
335 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 mOpenHelper = new DatabaseHelper(getContext());
337 }
338
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700339 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700341 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700342 private long mMaxItemId = -1;
343 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344
Winson Chung0b560dd2014-01-21 13:00:26 -0800345 private boolean mNewDbCreated = false;
346
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100348 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700350 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700351
352 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
353 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700354 if (mMaxItemId == -1) {
355 mMaxItemId = initializeMaxItemId(getWritableDatabase());
356 }
357 if (mMaxScreenId == -1) {
358 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700359 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 }
361
Winson Chung0b560dd2014-01-21 13:00:26 -0800362 public boolean wasNewDbCreated() {
363 return mNewDbCreated;
364 }
365
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700366 /**
367 * Send notification that we've deleted the {@link AppWidgetHost},
368 * probably as part of the initial database creation. The receiver may
369 * want to re-call {@link AppWidgetHost#startListening()} to ensure
370 * callbacks are correctly set.
371 */
372 private void sendAppWidgetResetNotify() {
373 final ContentResolver resolver = mContext.getContentResolver();
374 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
375 }
376
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800377 @Override
378 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800379 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700380
Adam Cohendcd297f2013-06-18 13:13:40 -0700381 mMaxItemId = 1;
382 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800383 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700384
Kenny Guyed131872014-04-30 03:02:21 +0100385 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
386 long userSerialNumber = userManager.getSerialNumberForUser(
387 UserHandleCompat.myUserHandle());
388
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 db.execSQL("CREATE TABLE favorites (" +
390 "_id INTEGER PRIMARY KEY," +
391 "title TEXT," +
392 "intent TEXT," +
393 "container INTEGER," +
394 "screen INTEGER," +
395 "cellX INTEGER," +
396 "cellY INTEGER," +
397 "spanX INTEGER," +
398 "spanY INTEGER," +
399 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700400 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800401 "isShortcut INTEGER," +
402 "iconType INTEGER," +
403 "iconPackage TEXT," +
404 "iconResource TEXT," +
405 "icon BLOB," +
406 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400407 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400408 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500409 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100410 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800411 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
412 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800413 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700414 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800415
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700416 // Database was just created, so wipe any previous widgets
417 if (mAppWidgetHost != null) {
418 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700419 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800420 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700421
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800422 // Fresh and clean launcher DB.
423 mMaxItemId = initializeMaxItemId(db);
424 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 }
426
Adam Cohendcd297f2013-06-18 13:13:40 -0700427 private void addWorkspacesTable(SQLiteDatabase db) {
428 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800429 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400430 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
431 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 ");");
433 }
434
Adam Cohen119285e2014-04-02 16:59:08 -0700435 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700436 // Delete items directly on the workspace who's screen id doesn't exist
437 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
438 // AND container = -100"
439 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
440 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700441 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700442 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
443 " AND " +
444 LauncherSettings.Favorites.CONTAINER + " = " +
445 LauncherSettings.Favorites.CONTAINER_DESKTOP;
446 db.execSQL(removeOrphanedDesktopItems);
447
448 // Delete items contained in folders which no longer exist (after above statement)
449 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
450 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
451 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
452 " WHERE " +
453 LauncherSettings.Favorites.CONTAINER + " <> " +
454 LauncherSettings.Favorites.CONTAINER_DESKTOP +
455 " AND "
456 + LauncherSettings.Favorites.CONTAINER + " <> " +
457 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
458 " AND "
459 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
460 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
461 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
462 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
463 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700464 }
465
Winson Chungc763c4e2013-07-19 13:49:06 -0700466 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400467 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700468 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800469 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700470 }
471
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 private void setFlagEmptyDbCreated() {
473 String spKey = LauncherAppState.getSharedPreferencesKey();
474 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800475 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700476 }
477
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800478 @Override
479 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700480 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800481 switch (oldVersion) {
482 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800483 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800484 case 12: {
485 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
486 // to persist workspace screens and their relative order.
487 mMaxScreenId = 0;
488 addWorkspacesTable(db);
489 }
490 case 13: {
491 db.beginTransaction();
492 try {
493 // Insert new column for holding widget provider name
494 db.execSQL("ALTER TABLE favorites " +
495 "ADD COLUMN appWidgetProvider TEXT;");
496 db.setTransactionSuccessful();
497 } catch (SQLException ex) {
498 Log.e(TAG, ex.getMessage(), ex);
499 // Old version remains, which means we wipe old data
500 break;
501 } finally {
502 db.endTransaction();
503 }
504 }
505 case 14: {
506 db.beginTransaction();
507 try {
508 // Insert new column for holding update timestamp
509 db.execSQL("ALTER TABLE favorites " +
510 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
511 db.execSQL("ALTER TABLE workspaceScreens " +
512 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
513 db.setTransactionSuccessful();
514 } catch (SQLException ex) {
515 Log.e(TAG, ex.getMessage(), ex);
516 // Old version remains, which means we wipe old data
517 break;
518 } finally {
519 db.endTransaction();
520 }
521 }
522 case 15: {
523 db.beginTransaction();
524 try {
525 // Insert new column for holding restore status
526 db.execSQL("ALTER TABLE favorites " +
527 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
528 db.setTransactionSuccessful();
529 } catch (SQLException ex) {
530 Log.e(TAG, ex.getMessage(), ex);
531 // Old version remains, which means we wipe old data
532 break;
533 } finally {
534 db.endTransaction();
535 }
536 }
537 case 16: {
538 // We use the db version upgrade here to identify users who may not have seen
539 // clings yet (because they weren't available), but for whom the clings are now
540 // available (tablet users). Because one of the possible cling flows (migration)
541 // is very destructive (wipes out workspaces), we want to prevent this from showing
542 // until clear data. We do so by marking that the clings have been shown.
543 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
544 }
545 case 17: {
546 // No-op
547 }
548 case 18: {
549 // Due to a data loss bug, some users may have items associated with screen ids
550 // which no longer exist. Since this can cause other problems, and since the user
551 // will never see these items anyway, we use database upgrade as an opportunity to
552 // clean things up.
553 removeOrphanedItems(db);
554 }
555 case 19: {
556 // Add userId column
557 if (!addProfileColumn(db)) {
558 // Old version remains, which means we wipe old data
559 break;
560 }
561 }
562 case 20:
563 if (!updateFolderItemsRank(db, true)) {
564 break;
565 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800566 case 21:
567 // Recreate workspace table with screen id a primary key
568 if (!recreateWorkspaceTable(db)) {
569 break;
570 }
571 case 22: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800572 // DB Upgraded successfully
573 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400574 }
575 }
576
Sunny Goyala2cc6242015-01-14 14:23:02 -0800577 // DB was not upgraded
578 Log.w(TAG, "Destroying all old data.");
579 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800580 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800581
Adam Cohen9b1d0622014-05-21 19:01:57 -0700582 @Override
583 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
584 // This shouldn't happen -- throw our hands up in the air and start over.
585 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
586 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700587 createEmptyDB(db);
588 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700589
Sunny Goyal42de82f2014-09-26 22:09:29 -0700590
591 /**
592 * Clears all the data for a fresh start.
593 */
594 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700595 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
596 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
597 onCreate(db);
598 }
599
Sunny Goyald2f38192015-02-25 10:46:34 -0800600 /**
601 * Recreates workspace table and migrates data to the new table.
602 */
603 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
604 db.beginTransaction();
605 try {
606 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
607 new String[] {LauncherSettings.WorkspaceScreens._ID},
608 null, null, null, null,
609 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
610 ArrayList<Long> sortedIDs = new ArrayList<Long>();
611 long maxId = 0;
612 try {
613 while (c.moveToNext()) {
614 Long id = c.getLong(0);
615 if (!sortedIDs.contains(id)) {
616 sortedIDs.add(id);
617 maxId = Math.max(maxId, id);
618 }
619 }
620 } finally {
621 c.close();
622 }
623
624 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
625 addWorkspacesTable(db);
626
627 // Add all screen ids back
628 int total = sortedIDs.size();
629 for (int i = 0; i < total; i++) {
630 ContentValues values = new ContentValues();
631 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
632 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
633 addModifiedTime(values);
634 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
635 }
636 db.setTransactionSuccessful();
637 mMaxScreenId = maxId;
638 } catch (SQLException ex) {
639 // Old version remains, which means we wipe old data
640 Log.e(TAG, ex.getMessage(), ex);
641 return false;
642 } finally {
643 db.endTransaction();
644 }
645 return true;
646 }
647
Sunny Goyal08f72612015-01-05 13:41:43 -0800648 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
649 db.beginTransaction();
650 try {
651 if (addRankColumn) {
652 // Insert new column for holding rank
653 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
654 }
655
656 // Get a map for folder ID to folder width
657 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
658 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
659 + " GROUP BY container;",
660 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
661
662 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800663 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
664 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800665 new Object[] {c.getLong(1) + 1, c.getLong(0)});
666 }
667
668 c.close();
669 db.setTransactionSuccessful();
670 } catch (SQLException ex) {
671 // Old version remains, which means we wipe old data
672 Log.e(TAG, ex.getMessage(), ex);
673 return false;
674 } finally {
675 db.endTransaction();
676 }
677 return true;
678 }
679
Kenny Guyed131872014-04-30 03:02:21 +0100680 private boolean addProfileColumn(SQLiteDatabase db) {
681 db.beginTransaction();
682 try {
683 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 // Insert new column for holding user serial number
689 db.execSQL("ALTER TABLE favorites " +
690 "ADD COLUMN profileId INTEGER DEFAULT "
691 + userSerialNumber + ";");
692 db.setTransactionSuccessful();
693 } catch (SQLException ex) {
694 // Old version remains, which means we wipe old data
695 Log.e(TAG, ex.getMessage(), ex);
696 return false;
697 } finally {
698 db.endTransaction();
699 }
700 return true;
701 }
702
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700703 // Generates a new ID to use for an object in your database. This method should be only
704 // called from the main UI thread. As an exception, we do call it when we call the
705 // constructor from the worker thread; however, this doesn't extend until after the
706 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
707 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700708 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700709 public long generateNewItemId() {
710 if (mMaxItemId < 0) {
711 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700712 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 mMaxItemId += 1;
714 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700715 }
716
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700717 @Override
718 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
719 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
720 }
721
Winson Chungc763c4e2013-07-19 13:49:06 -0700722 public void updateMaxItemId(long id) {
723 mMaxItemId = id + 1;
724 }
725
Chris Wren5dee7af2013-12-20 17:22:11 -0500726 public void checkId(String table, ContentValues values) {
727 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
728 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
729 mMaxScreenId = Math.max(id, mMaxScreenId);
730 } else {
731 mMaxItemId = Math.max(id, mMaxItemId);
732 }
733 }
734
Adam Cohendcd297f2013-06-18 13:13:40 -0700735 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700736 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
737
738 // get the result
739 final int maxIdIndex = 0;
740 long id = -1;
741 if (c != null && c.moveToNext()) {
742 id = c.getLong(maxIdIndex);
743 }
Michael Jurka5130e402011-10-13 04:55:35 -0700744 if (c != null) {
745 c.close();
746 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700747
748 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700749 throw new RuntimeException("Error: could not query max item id");
750 }
751
752 return id;
753 }
754
755 // Generates a new ID to use for an workspace screen in your database. This method
756 // should be only called from the main UI thread. As an exception, we do call it when we
757 // call the constructor from the worker thread; however, this doesn't extend until after the
758 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
759 // after that point
760 public long generateNewScreenId() {
761 if (mMaxScreenId < 0) {
762 throw new RuntimeException("Error: max screen id was not initialized");
763 }
764 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800765 // Log to disk
766 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700767 return mMaxScreenId;
768 }
769
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 private long initializeMaxScreenId(SQLiteDatabase db) {
771 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
772
773 // get the result
774 final int maxIdIndex = 0;
775 long id = -1;
776 if (c != null && c.moveToNext()) {
777 id = c.getLong(maxIdIndex);
778 }
779 if (c != null) {
780 c.close();
781 }
782
783 if (id == -1) {
784 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700785 }
786
Winson Chunga90303b2013-11-15 13:05:06 -0800787 // Log to disk
788 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700789 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800790 }
791
Adam Cohena043fa82014-07-23 14:49:38 -0700792 private boolean initializeExternalAdd(ContentValues values) {
793 // 1. Ensure that externally added items have a valid item id
794 long id = generateNewItemId();
795 values.put(LauncherSettings.Favorites._ID, id);
796
797 // 2. In the case of an app widget, and if no app widget id is specified, we
798 // attempt allocate and bind the widget.
799 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
800 if (itemType != null &&
801 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
802 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
803
804 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
805 ComponentName cn = ComponentName.unflattenFromString(
806 values.getAsString(Favorites.APPWIDGET_PROVIDER));
807
808 if (cn != null) {
809 try {
810 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700811 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700812 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700813 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700814 }
815 } catch (RuntimeException e) {
816 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700817 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700818 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700819 } else {
820 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700821 }
822 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700823
824 // Add screen id if not present
825 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
826 if (!addScreenIdIfNecessary(screenId)) {
827 return false;
828 }
Adam Cohena043fa82014-07-23 14:49:38 -0700829 return true;
830 }
831
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700832 // Returns true of screen id exists, or if successfully added
833 private boolean addScreenIdIfNecessary(long screenId) {
834 if (!hasScreenId(screenId)) {
835 int rank = getMaxScreenRank() + 1;
836
837 ContentValues v = new ContentValues();
838 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
839 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
840 if (dbInsertAndCheck(this, getWritableDatabase(),
841 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
842 return false;
843 }
844 }
845 return true;
846 }
847
848 private boolean hasScreenId(long screenId) {
849 SQLiteDatabase db = getWritableDatabase();
850 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
851 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
852 if (c != null) {
853 int count = c.getCount();
854 c.close();
855 return count > 0;
856 } else {
857 return false;
858 }
859 }
860
861 private int getMaxScreenRank() {
862 SQLiteDatabase db = getWritableDatabase();
863 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
864 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
865
866 // get the result
867 final int maxRankIndex = 0;
868 int rank = -1;
869 if (c != null && c.moveToNext()) {
870 rank = c.getInt(maxRankIndex);
871 }
872 if (c != null) {
873 c.close();
874 }
875
876 return rank;
877 }
878
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700879 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700880 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700881 // TODO: Use multiple loaders with fall-back and transaction.
882 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700883
884 // Add the screens specified by the items above
885 Collections.sort(screenIds);
886 int rank = 0;
887 ContentValues values = new ContentValues();
888 for (Long id : screenIds) {
889 values.clear();
890 values.put(LauncherSettings.WorkspaceScreens._ID, id);
891 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
892 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
893 throw new RuntimeException("Failed initialize screen table"
894 + "from default layout");
895 }
896 rank++;
897 }
898
899 // Ensure that the max ids are initialized
900 mMaxItemId = initializeMaxItemId(db);
901 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700902
Adam Cohen71483f42014-05-15 14:04:01 -0700903 return count;
904 }
905
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700906 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500907 final ContentResolver resolver = mContext.getContentResolver();
908 Cursor c = null;
909 int count = 0;
910 int curScreen = 0;
911
912 try {
913 c = resolver.query(uri, null, null, null, "title ASC");
914 } catch (Exception e) {
915 // Ignore
916 }
917
Dan Sandlerd5024042014-01-09 15:01:33 -0500918 // We already have a favorites database in the old provider
919 if (c != null) {
920 try {
921 if (c.getCount() > 0) {
922 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
923 final int intentIndex
924 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
925 final int titleIndex
926 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
927 final int iconTypeIndex
928 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
929 final int iconIndex
930 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
931 final int iconPackageIndex
932 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
933 final int iconResourceIndex
934 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
935 final int containerIndex
936 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
937 final int itemTypeIndex
938 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
939 final int screenIndex
940 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
941 final int cellXIndex
942 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
943 final int cellYIndex
944 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
945 final int uriIndex
946 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
947 final int displayModeIndex
948 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100949 final int profileIndex
950 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500951
952 int i = 0;
953 int curX = 0;
954 int curY = 0;
955
956 final LauncherAppState app = LauncherAppState.getInstance();
957 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
958 final int width = (int) grid.numColumns;
959 final int height = (int) grid.numRows;
960 final int hotseatWidth = (int) grid.numHotseatIcons;
961
962 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
963
Adam Cohen72960972014-01-15 18:13:55 -0800964 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
965 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500966 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500967
968 while (c.moveToNext()) {
969 final int itemType = c.getInt(itemTypeIndex);
970 if (itemType != Favorites.ITEM_TYPE_APPLICATION
971 && itemType != Favorites.ITEM_TYPE_SHORTCUT
972 && itemType != Favorites.ITEM_TYPE_FOLDER) {
973 continue;
974 }
975
976 final int cellX = c.getInt(cellXIndex);
977 final int cellY = c.getInt(cellYIndex);
978 final int screen = c.getInt(screenIndex);
979 int container = c.getInt(containerIndex);
980 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100981
982 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
983 UserHandleCompat userHandle;
984 final long userSerialNumber;
985 if (profileIndex != -1 && !c.isNull(profileIndex)) {
986 userSerialNumber = c.getInt(profileIndex);
987 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
988 } else {
989 // Default to the serial number of this user, for older
990 // shortcuts.
991 userHandle = UserHandleCompat.myUserHandle();
992 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
993 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800994
995 if (userHandle == null) {
996 Launcher.addDumpLog(TAG, "skipping deleted user", true);
997 continue;
998 }
999
Dan Sandlerd5024042014-01-09 15:01:33 -05001000 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001001 + c.getString(titleIndex) + "\" ("
1002 + cellX + "," + cellY + "@"
1003 + LauncherSettings.Favorites.containerToString(container)
1004 + "/" + screen
1005 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001006
1007 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001008
1009 final Intent intent;
1010 final ComponentName cn;
1011 try {
1012 intent = Intent.parseUri(intentStr, 0);
1013 } catch (URISyntaxException e) {
1014 // bogus intent?
1015 Launcher.addDumpLog(TAG,
1016 "skipping invalid intent uri", true);
1017 continue;
1018 }
1019
1020 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001021 if (TextUtils.isEmpty(intentStr)) {
1022 // no intent? no icon
1023 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1024 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001025 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001026 !LauncherModel.isValidPackageActivity(mContext, cn,
1027 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001028 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001029 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001030 "no longer exists.", true);
1031 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001032 } else if (container ==
1033 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1034 // Dedupe icons directly on the workspace
1035
Adam Cohen556f6132014-01-15 15:18:08 -08001036 // Canonicalize
1037 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001038 // does not, so we clear that out to keep them the same.
1039 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001040 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001041 int flags = intent.getFlags();
1042 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001043 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001044 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001045 if (seenIntents.contains(key)) {
1046 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001047 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001048 } else {
1049 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001050 }
1051 }
1052 }
1053
1054 ContentValues values = new ContentValues(c.getColumnCount());
1055 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1056 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1057 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1058 values.put(LauncherSettings.Favorites.ICON_TYPE,
1059 c.getInt(iconTypeIndex));
1060 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1061 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1062 c.getString(iconPackageIndex));
1063 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1064 c.getString(iconResourceIndex));
1065 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1066 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1067 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1068 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1069 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001070 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001071
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001072 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1073 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001074 }
1075
1076 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1077 // In a folder or in the hotseat, preserve position
1078 values.put(LauncherSettings.Favorites.SCREEN, screen);
1079 values.put(LauncherSettings.Favorites.CELLX, cellX);
1080 values.put(LauncherSettings.Favorites.CELLY, cellY);
1081 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001082 // For items contained directly on one of the workspace screen,
1083 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001084 }
1085
1086 values.put(LauncherSettings.Favorites.CONTAINER, container);
1087
Adam Cohen72960972014-01-15 18:13:55 -08001088 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1089 shortcuts.add(values);
1090 } else {
1091 folders.add(values);
1092 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001093 }
1094
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001095 // Now that we have all the hotseat icons, let's go through them left-right
1096 // and assign valid locations for them in the new hotseat
1097 final int N = hotseat.size();
1098 for (int idx=0; idx<N; idx++) {
1099 int hotseatX = hotseat.keyAt(idx);
1100 ContentValues values = hotseat.valueAt(idx);
1101
1102 if (hotseatX == grid.hotseatAllAppsRank) {
1103 // let's drop this in the next available hole in the hotseat
1104 while (++hotseatX < hotseatWidth) {
1105 if (hotseat.get(hotseatX) == null) {
1106 // found a spot! move it here
1107 values.put(LauncherSettings.Favorites.SCREEN,
1108 hotseatX);
1109 break;
1110 }
1111 }
1112 }
1113 if (hotseatX >= hotseatWidth) {
1114 // no room for you in the hotseat? it's off to the desktop with you
1115 values.put(LauncherSettings.Favorites.CONTAINER,
1116 Favorites.CONTAINER_DESKTOP);
1117 }
1118 }
1119
Adam Cohen72960972014-01-15 18:13:55 -08001120 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1121 // Folders first
1122 allItems.addAll(folders);
1123 // Then shortcuts
1124 allItems.addAll(shortcuts);
1125
1126 // Layout all the folders
1127 for (ContentValues values: allItems) {
1128 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1129 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1130 // Hotseat items and folder items have already had their
1131 // location information set. Nothing to be done here.
1132 continue;
1133 }
1134 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1135 values.put(LauncherSettings.Favorites.CELLX, curX);
1136 values.put(LauncherSettings.Favorites.CELLY, curY);
1137 curX = (curX + 1) % width;
1138 if (curX == 0) {
1139 curY = (curY + 1);
1140 }
1141 // Leave the last row of icons blank on every screen
1142 if (curY == height - 1) {
1143 curScreen = (int) generateNewScreenId();
1144 curY = 0;
1145 }
1146 }
1147
1148 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001149 db.beginTransaction();
1150 try {
Adam Cohen72960972014-01-15 18:13:55 -08001151 for (ContentValues row: allItems) {
1152 if (row == null) continue;
1153 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001154 < 0) {
1155 return;
1156 } else {
1157 count++;
1158 }
1159 }
1160 db.setTransactionSuccessful();
1161 } finally {
1162 db.endTransaction();
1163 }
1164 }
1165
1166 db.beginTransaction();
1167 try {
1168 for (i=0; i<=curScreen; i++) {
1169 final ContentValues values = new ContentValues();
1170 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1171 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1172 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1173 < 0) {
1174 return;
1175 }
1176 }
1177 db.setTransactionSuccessful();
1178 } finally {
1179 db.endTransaction();
1180 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001181
1182 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001183 }
1184 } finally {
1185 c.close();
1186 }
1187 }
1188
1189 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1190 + (curScreen+1) + " screens", true);
1191
1192 // ensure that new screens are created to hold these icons
1193 setFlagJustLoadedOldDb();
1194
1195 // Update max IDs; very important since we just grabbed IDs from another database
1196 mMaxItemId = initializeMaxItemId(db);
1197 mMaxScreenId = initializeMaxScreenId(db);
1198 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1199 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001200 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001201
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001202 static class SqlArguments {
1203 public final String table;
1204 public final String where;
1205 public final String[] args;
1206
1207 SqlArguments(Uri url, String where, String[] args) {
1208 if (url.getPathSegments().size() == 1) {
1209 this.table = url.getPathSegments().get(0);
1210 this.where = where;
1211 this.args = args;
1212 } else if (url.getPathSegments().size() != 2) {
1213 throw new IllegalArgumentException("Invalid URI: " + url);
1214 } else if (!TextUtils.isEmpty(where)) {
1215 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1216 } else {
1217 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001218 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001219 this.args = null;
1220 }
1221 }
1222
1223 SqlArguments(Uri url) {
1224 if (url.getPathSegments().size() == 1) {
1225 table = url.getPathSegments().get(0);
1226 where = null;
1227 args = null;
1228 } else {
1229 throw new IllegalArgumentException("Invalid URI: " + url);
1230 }
1231 }
1232 }
Adam Cohen72960972014-01-15 18:13:55 -08001233}