blob: 4bdbdf407e42e6cccc43e4f860befb97f91f2f90 [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 Goyale87e6ab2014-11-21 22:42:53 -080060 private static final int MIN_DATABASE_VERSION = 12;
Sunny Goyal08f72612015-01-05 13:41:43 -080061 private static final int DATABASE_VERSION = 21;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062
Adam Cohene25af792013-06-06 23:08:25 -070063 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040064 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070067 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080069 static final String UPGRADED_FROM_OLD_DATABASE = "UPGRADED_FROM_OLD_DATABASE";
70 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Adam Cohena043fa82014-07-23 14:49:38 -070072 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
73
Anjali Koppal67e7cae2014-03-13 12:14:12 -070074 private LauncherProviderChangeListener mListener;
75
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070076 /**
Romain Guy73b979d2009-06-09 12:57:21 -070077 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070078 * {@link AppWidgetHost#deleteHost()} is called during database creation.
79 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
80 */
81 static final Uri CONTENT_APPWIDGET_RESET_URI =
82 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070083
Michael Jurkaa8c760d2011-04-28 14:59:33 -070084 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085
86 @Override
87 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 final Context context = getContext();
Nilesh Agrawalfde11852015-01-21 11:50:57 -080089 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080091 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093 return true;
94 }
95
Winson Chung0b560dd2014-01-21 13:00:26 -080096 public boolean wasNewDbCreated() {
97 return mOpenHelper.wasNewDbCreated();
98 }
99
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700100 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
101 mListener = listener;
102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
114 @Override
115 public Cursor query(Uri uri, String[] projection, String selection,
116 String[] selectionArgs, String sortOrder) {
117
118 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
119 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
120 qb.setTables(args.table);
121
Romain Guy73b979d2009-06-09 12:57:21 -0700122 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
124 result.setNotificationUri(getContext().getContentResolver(), uri);
125
126 return result;
127 }
128
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 private static long dbInsertAndCheck(DatabaseHelper helper,
130 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500131 if (values == null) {
132 throw new RuntimeException("Error: attempting to insert null values");
133 }
Adam Cohen71483f42014-05-15 14:04:01 -0700134 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 throw new RuntimeException("Error: attempting to add item without specifying an id");
136 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500137 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 return db.insert(table, nullColumnHack, values);
139 }
140
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141 @Override
142 public Uri insert(Uri uri, ContentValues initialValues) {
143 SqlArguments args = new SqlArguments(uri);
144
Adam Cohena043fa82014-07-23 14:49:38 -0700145 // In very limited cases, we support system|signature permission apps to add to the db
146 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
147 if (externalAdd != null && "true".equals(externalAdd)) {
148 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
149 return null;
150 }
151 }
152
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400154 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156 if (rowId <= 0) return null;
157
158 uri = ContentUris.withAppendedId(uri, rowId);
159 sendNotify(uri);
160
161 return uri;
162 }
163
Adam Cohena043fa82014-07-23 14:49:38 -0700164
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165 @Override
166 public int bulkInsert(Uri uri, ContentValues[] values) {
167 SqlArguments args = new SqlArguments(uri);
168
169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
170 db.beginTransaction();
171 try {
172 int numValues = values.length;
173 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400174 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
176 return 0;
177 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178 }
179 db.setTransactionSuccessful();
180 } finally {
181 db.endTransaction();
182 }
183
184 sendNotify(uri);
185 return values.length;
186 }
187
188 @Override
Yura085c8532014-02-11 15:15:29 +0000189 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
190 throws OperationApplicationException {
191 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
192 db.beginTransaction();
193 try {
194 ContentProviderResult[] result = super.applyBatch(operations);
195 db.setTransactionSuccessful();
196 return result;
197 } finally {
198 db.endTransaction();
199 }
200 }
201
202 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 public int delete(Uri uri, String selection, String[] selectionArgs) {
204 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
205
206 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
207 int count = db.delete(args.table, args.where, args.args);
208 if (count > 0) sendNotify(uri);
209
210 return count;
211 }
212
213 @Override
214 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
215 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
216
Chris Wren1ada10d2013-09-13 18:01:38 -0400217 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
219 int count = db.update(args.table, values, args.where, args.args);
220 if (count > 0) sendNotify(uri);
221
222 return count;
223 }
224
225 private void sendNotify(Uri uri) {
226 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400230
231 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400232 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700233 if (mListener != null) {
234 mListener.onLauncherProviderChange();
235 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400236 }
237
238 private void addModifiedTime(ContentValues values) {
239 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240 }
241
Adam Cohendcd297f2013-06-18 13:13:40 -0700242 public long generateNewItemId() {
243 return mOpenHelper.generateNewItemId();
244 }
245
Winson Chungc763c4e2013-07-19 13:49:06 -0700246 public void updateMaxItemId(long id) {
247 mOpenHelper.updateMaxItemId(id);
248 }
249
Adam Cohendcd297f2013-06-18 13:13:40 -0700250 public long generateNewScreenId() {
251 return mOpenHelper.generateNewScreenId();
252 }
253
254 // This is only required one time while loading the workspace during the
255 // upgrade path, and should never be called from anywhere else.
256 public void updateMaxScreenId(long maxScreenId) {
257 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700258 }
259
Brian Muramatsu5524b492012-10-02 16:55:54 -0700260 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700261 * Clears all the data for a fresh start.
262 */
263 synchronized public void createEmptyDB() {
264 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
265 }
266
Sunny Goyal33d44382014-10-16 09:24:19 -0700267 public void clearFlagEmptyDbCreated() {
268 String spKey = LauncherAppState.getSharedPreferencesKey();
269 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
270 .edit()
271 .remove(EMPTY_DATABASE_CREATED)
272 .commit();
273 }
274
Sunny Goyal42de82f2014-09-26 22:09:29 -0700275 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700276 * Loads the default workspace based on the following priority scheme:
277 * 1) From a package provided by play store
278 * 2) From a partner configuration APK, already in the system image
279 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700280 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700281 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400282 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700283 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700284
Winson Chungc763c4e2013-07-19 13:49:06 -0700285 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500286 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200287
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700288 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700289 mOpenHelper.mAppWidgetHost, mOpenHelper);
290
291 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700292 final Partner partner = Partner.get(getContext().getPackageManager());
293 if (partner != null && partner.hasDefaultLayout()) {
294 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700295 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700296 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700297 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700298 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
299 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700300 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700301 }
302 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700303
Sunny Goyal9d219682014-10-23 14:21:02 -0700304 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700305 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700306 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700307 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700308 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700309 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
310 && usingExternallyProvidedLayout) {
311 // Unable to load external layout. Cleanup and load the internal layout.
312 createEmptyDB();
313 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
314 getDefaultLayoutParser());
315 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700316 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700317 }
318 }
319
Sunny Goyal9d219682014-10-23 14:21:02 -0700320 private DefaultLayoutParser getDefaultLayoutParser() {
321 int defaultLayout = LauncherAppState.getInstance()
322 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
323 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
324 mOpenHelper, getContext().getResources(), defaultLayout);
325 }
326
Dan Sandlerd5024042014-01-09 15:01:33 -0500327 public void migrateLauncher2Shortcuts() {
328 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400329 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500330 }
331
Sunny Goyal08f72612015-01-05 13:41:43 -0800332 public void updateFolderItemsRank() {
333 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
334 }
335
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 public void deleteDatabase() {
337 // Are you sure? (y/n)
338 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500339 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500340 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500341 if (dbFile.exists()) {
342 SQLiteDatabase.deleteDatabase(dbFile);
343 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500344 mOpenHelper = new DatabaseHelper(getContext());
345 }
346
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700347 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700349 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700350 private long mMaxItemId = -1;
351 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352
Winson Chung0b560dd2014-01-21 13:00:26 -0800353 private boolean mNewDbCreated = false;
354
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100356 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700358 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700359
360 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
361 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700362 if (mMaxItemId == -1) {
363 mMaxItemId = initializeMaxItemId(getWritableDatabase());
364 }
365 if (mMaxScreenId == -1) {
366 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700367 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 }
369
Winson Chung0b560dd2014-01-21 13:00:26 -0800370 public boolean wasNewDbCreated() {
371 return mNewDbCreated;
372 }
373
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700374 /**
375 * Send notification that we've deleted the {@link AppWidgetHost},
376 * probably as part of the initial database creation. The receiver may
377 * want to re-call {@link AppWidgetHost#startListening()} to ensure
378 * callbacks are correctly set.
379 */
380 private void sendAppWidgetResetNotify() {
381 final ContentResolver resolver = mContext.getContentResolver();
382 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
383 }
384
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800385 @Override
386 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800387 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700388
Adam Cohendcd297f2013-06-18 13:13:40 -0700389 mMaxItemId = 1;
390 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800391 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700392
Kenny Guyed131872014-04-30 03:02:21 +0100393 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
394 long userSerialNumber = userManager.getSerialNumberForUser(
395 UserHandleCompat.myUserHandle());
396
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 db.execSQL("CREATE TABLE favorites (" +
398 "_id INTEGER PRIMARY KEY," +
399 "title TEXT," +
400 "intent TEXT," +
401 "container INTEGER," +
402 "screen INTEGER," +
403 "cellX INTEGER," +
404 "cellY INTEGER," +
405 "spanX INTEGER," +
406 "spanY INTEGER," +
407 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700408 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800409 "isShortcut INTEGER," +
410 "iconType INTEGER," +
411 "iconPackage TEXT," +
412 "iconResource TEXT," +
413 "icon BLOB," +
414 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400415 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400416 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500417 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100418 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800419 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
420 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800421 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700422 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800423
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700424 // Database was just created, so wipe any previous widgets
425 if (mAppWidgetHost != null) {
426 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700427 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800428 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700429
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800430 // Fresh and clean launcher DB.
431 mMaxItemId = initializeMaxItemId(db);
432 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800433 }
434
Adam Cohendcd297f2013-06-18 13:13:40 -0700435 private void addWorkspacesTable(SQLiteDatabase db) {
436 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
437 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400438 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
439 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700440 ");");
441 }
442
Adam Cohen119285e2014-04-02 16:59:08 -0700443 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700444 // Delete items directly on the workspace who's screen id doesn't exist
445 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
446 // AND container = -100"
447 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
448 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700449 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700450 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
451 " AND " +
452 LauncherSettings.Favorites.CONTAINER + " = " +
453 LauncherSettings.Favorites.CONTAINER_DESKTOP;
454 db.execSQL(removeOrphanedDesktopItems);
455
456 // Delete items contained in folders which no longer exist (after above statement)
457 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
458 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
459 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
460 " WHERE " +
461 LauncherSettings.Favorites.CONTAINER + " <> " +
462 LauncherSettings.Favorites.CONTAINER_DESKTOP +
463 " AND "
464 + LauncherSettings.Favorites.CONTAINER + " <> " +
465 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
466 " AND "
467 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
468 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
469 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
470 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
471 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700472 }
473
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400475 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700476 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
477 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700478 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
479 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700480 editor.commit();
481 }
482
Winson Chungc763c4e2013-07-19 13:49:06 -0700483 private void setFlagEmptyDbCreated() {
484 String spKey = LauncherAppState.getSharedPreferencesKey();
485 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
486 SharedPreferences.Editor editor = sp.edit();
487 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
488 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
489 editor.commit();
490 }
491
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492 @Override
493 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700494 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700495
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 int version = oldVersion;
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800497 if (version < MIN_DATABASE_VERSION) {
498 // The version cannot be lower that this, as Launcher3 never supported a lower
499 // version of the DB.
500 createEmptyDB(db);
501 version = DATABASE_VERSION;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700502 }
503
Adam Cohendcd297f2013-06-18 13:13:40 -0700504 if (version < 13) {
505 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
506 // to persist workspace screens and their relative order.
507 mMaxScreenId = 0;
508
Adam Cohendcd297f2013-06-18 13:13:40 -0700509 addWorkspacesTable(db);
510 version = 13;
511 }
512
Chris Wrend5e66bf2013-09-16 14:02:29 -0400513 if (version < 14) {
514 db.beginTransaction();
515 try {
516 // Insert new column for holding widget provider name
517 db.execSQL("ALTER TABLE favorites " +
518 "ADD COLUMN appWidgetProvider TEXT;");
519 db.setTransactionSuccessful();
520 version = 14;
521 } catch (SQLException ex) {
522 // Old version remains, which means we wipe old data
523 Log.e(TAG, ex.getMessage(), ex);
524 } finally {
525 db.endTransaction();
526 }
527 }
528
Chris Wren1ada10d2013-09-13 18:01:38 -0400529 if (version < 15) {
530 db.beginTransaction();
531 try {
532 // Insert new column for holding update timestamp
533 db.execSQL("ALTER TABLE favorites " +
534 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
535 db.execSQL("ALTER TABLE workspaceScreens " +
536 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
537 db.setTransactionSuccessful();
538 version = 15;
539 } catch (SQLException ex) {
540 // Old version remains, which means we wipe old data
541 Log.e(TAG, ex.getMessage(), ex);
542 } finally {
543 db.endTransaction();
544 }
545 }
546
Chris Wrenf4d08112014-01-16 18:13:56 -0500547
548 if (version < 16) {
549 db.beginTransaction();
550 try {
551 // Insert new column for holding restore status
552 db.execSQL("ALTER TABLE favorites " +
553 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
554 db.setTransactionSuccessful();
555 version = 16;
556 } catch (SQLException ex) {
557 // Old version remains, which means we wipe old data
558 Log.e(TAG, ex.getMessage(), ex);
559 } finally {
560 db.endTransaction();
561 }
562 }
563
Adam Cohen71e03b92014-02-21 14:09:53 -0800564 if (version < 17) {
565 // We use the db version upgrade here to identify users who may not have seen
566 // clings yet (because they weren't available), but for whom the clings are now
567 // available (tablet users). Because one of the possible cling flows (migration)
568 // is very destructive (wipes out workspaces), we want to prevent this from showing
569 // until clear data. We do so by marking that the clings have been shown.
570 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
571 version = 17;
572 }
573
Adam Cohen119285e2014-04-02 16:59:08 -0700574 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700575 // No-op
576 version = 18;
577 }
578
579 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700580 // Due to a data loss bug, some users may have items associated with screen ids
581 // which no longer exist. Since this can cause other problems, and since the user
582 // will never see these items anyway, we use database upgrade as an opportunity to
583 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700584 removeOrphanedItems(db);
585 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700586 }
587
Kenny Guyed131872014-04-30 03:02:21 +0100588 if (version < 20) {
589 // Add userId column
590 if (addProfileColumn(db)) {
591 version = 20;
592 }
593 // else old version remains, which means we wipe old data
594 }
595
Sunny Goyal08f72612015-01-05 13:41:43 -0800596 if (version < 21) {
597 if (updateFolderItemsRank(db, true)) {
598 version = 21;
599 }
600 }
601
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800603 Log.w(TAG, "Destroying all old data.");
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800604 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 }
606 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800607
Adam Cohen9b1d0622014-05-21 19:01:57 -0700608 @Override
609 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
610 // This shouldn't happen -- throw our hands up in the air and start over.
611 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
612 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700613 createEmptyDB(db);
614 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700615
Sunny Goyal42de82f2014-09-26 22:09:29 -0700616
617 /**
618 * Clears all the data for a fresh start.
619 */
620 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700621 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
622 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
623 onCreate(db);
624 }
625
Sunny Goyal08f72612015-01-05 13:41:43 -0800626 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
627 db.beginTransaction();
628 try {
629 if (addRankColumn) {
630 // Insert new column for holding rank
631 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
632 }
633
634 // Get a map for folder ID to folder width
635 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
636 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
637 + " GROUP BY container;",
638 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
639
640 while (c.moveToNext()) {
641 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE container=?;",
642 new Object[] {c.getLong(1) + 1, c.getLong(0)});
643 }
644
645 c.close();
646 db.setTransactionSuccessful();
647 } catch (SQLException ex) {
648 // Old version remains, which means we wipe old data
649 Log.e(TAG, ex.getMessage(), ex);
650 return false;
651 } finally {
652 db.endTransaction();
653 }
654 return true;
655 }
656
Kenny Guyed131872014-04-30 03:02:21 +0100657 private boolean addProfileColumn(SQLiteDatabase db) {
658 db.beginTransaction();
659 try {
660 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
661 // Default to the serial number of this user, for older
662 // shortcuts.
663 long userSerialNumber = userManager.getSerialNumberForUser(
664 UserHandleCompat.myUserHandle());
665 // Insert new column for holding user serial number
666 db.execSQL("ALTER TABLE favorites " +
667 "ADD COLUMN profileId INTEGER DEFAULT "
668 + userSerialNumber + ";");
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
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700680 // Generates a new ID to use for an object in your database. This method should be only
681 // called from the main UI thread. As an exception, we do call it when we call the
682 // constructor from the worker thread; however, this doesn't extend until after the
683 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
684 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700685 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700686 public long generateNewItemId() {
687 if (mMaxItemId < 0) {
688 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700689 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700690 mMaxItemId += 1;
691 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700692 }
693
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700694 @Override
695 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
696 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
697 }
698
Winson Chungc763c4e2013-07-19 13:49:06 -0700699 public void updateMaxItemId(long id) {
700 mMaxItemId = id + 1;
701 }
702
Chris Wren5dee7af2013-12-20 17:22:11 -0500703 public void checkId(String table, ContentValues values) {
704 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
705 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
706 mMaxScreenId = Math.max(id, mMaxScreenId);
707 } else {
708 mMaxItemId = Math.max(id, mMaxItemId);
709 }
710 }
711
Adam Cohendcd297f2013-06-18 13:13:40 -0700712 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700713 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
714
715 // get the result
716 final int maxIdIndex = 0;
717 long id = -1;
718 if (c != null && c.moveToNext()) {
719 id = c.getLong(maxIdIndex);
720 }
Michael Jurka5130e402011-10-13 04:55:35 -0700721 if (c != null) {
722 c.close();
723 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700724
725 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700726 throw new RuntimeException("Error: could not query max item id");
727 }
728
729 return id;
730 }
731
732 // Generates a new ID to use for an workspace screen in your database. This method
733 // should be only called from the main UI thread. As an exception, we do call it when we
734 // call the constructor from the worker thread; however, this doesn't extend until after the
735 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
736 // after that point
737 public long generateNewScreenId() {
738 if (mMaxScreenId < 0) {
739 throw new RuntimeException("Error: max screen id was not initialized");
740 }
741 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800742 // Log to disk
743 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700744 return mMaxScreenId;
745 }
746
747 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800748 // Log to disk
749 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700750 mMaxScreenId = maxScreenId;
751 }
752
753 private long initializeMaxScreenId(SQLiteDatabase db) {
754 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
755
756 // get the result
757 final int maxIdIndex = 0;
758 long id = -1;
759 if (c != null && c.moveToNext()) {
760 id = c.getLong(maxIdIndex);
761 }
762 if (c != null) {
763 c.close();
764 }
765
766 if (id == -1) {
767 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700768 }
769
Winson Chunga90303b2013-11-15 13:05:06 -0800770 // Log to disk
771 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700772 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800773 }
774
Adam Cohena043fa82014-07-23 14:49:38 -0700775 private boolean initializeExternalAdd(ContentValues values) {
776 // 1. Ensure that externally added items have a valid item id
777 long id = generateNewItemId();
778 values.put(LauncherSettings.Favorites._ID, id);
779
780 // 2. In the case of an app widget, and if no app widget id is specified, we
781 // attempt allocate and bind the widget.
782 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
783 if (itemType != null &&
784 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
785 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
786
787 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
788 ComponentName cn = ComponentName.unflattenFromString(
789 values.getAsString(Favorites.APPWIDGET_PROVIDER));
790
791 if (cn != null) {
792 try {
793 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700794 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700795 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700796 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700797 }
798 } catch (RuntimeException e) {
799 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700800 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700801 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700802 } else {
803 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700804 }
805 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700806
807 // Add screen id if not present
808 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
809 if (!addScreenIdIfNecessary(screenId)) {
810 return false;
811 }
Adam Cohena043fa82014-07-23 14:49:38 -0700812 return true;
813 }
814
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700815 // Returns true of screen id exists, or if successfully added
816 private boolean addScreenIdIfNecessary(long screenId) {
817 if (!hasScreenId(screenId)) {
818 int rank = getMaxScreenRank() + 1;
819
820 ContentValues v = new ContentValues();
821 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
822 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
823 if (dbInsertAndCheck(this, getWritableDatabase(),
824 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
825 return false;
826 }
827 }
828 return true;
829 }
830
831 private boolean hasScreenId(long screenId) {
832 SQLiteDatabase db = getWritableDatabase();
833 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
834 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
835 if (c != null) {
836 int count = c.getCount();
837 c.close();
838 return count > 0;
839 } else {
840 return false;
841 }
842 }
843
844 private int getMaxScreenRank() {
845 SQLiteDatabase db = getWritableDatabase();
846 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
847 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
848
849 // get the result
850 final int maxRankIndex = 0;
851 int rank = -1;
852 if (c != null && c.moveToNext()) {
853 rank = c.getInt(maxRankIndex);
854 }
855 if (c != null) {
856 c.close();
857 }
858
859 return rank;
860 }
861
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700862 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700863 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700864 // TODO: Use multiple loaders with fall-back and transaction.
865 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700866
867 // Add the screens specified by the items above
868 Collections.sort(screenIds);
869 int rank = 0;
870 ContentValues values = new ContentValues();
871 for (Long id : screenIds) {
872 values.clear();
873 values.put(LauncherSettings.WorkspaceScreens._ID, id);
874 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
875 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
876 throw new RuntimeException("Failed initialize screen table"
877 + "from default layout");
878 }
879 rank++;
880 }
881
882 // Ensure that the max ids are initialized
883 mMaxItemId = initializeMaxItemId(db);
884 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700885
Adam Cohen71483f42014-05-15 14:04:01 -0700886 return count;
887 }
888
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700889 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500890 final ContentResolver resolver = mContext.getContentResolver();
891 Cursor c = null;
892 int count = 0;
893 int curScreen = 0;
894
895 try {
896 c = resolver.query(uri, null, null, null, "title ASC");
897 } catch (Exception e) {
898 // Ignore
899 }
900
Dan Sandlerd5024042014-01-09 15:01:33 -0500901 // We already have a favorites database in the old provider
902 if (c != null) {
903 try {
904 if (c.getCount() > 0) {
905 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
906 final int intentIndex
907 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
908 final int titleIndex
909 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
910 final int iconTypeIndex
911 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
912 final int iconIndex
913 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
914 final int iconPackageIndex
915 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
916 final int iconResourceIndex
917 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
918 final int containerIndex
919 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
920 final int itemTypeIndex
921 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
922 final int screenIndex
923 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
924 final int cellXIndex
925 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
926 final int cellYIndex
927 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
928 final int uriIndex
929 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
930 final int displayModeIndex
931 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100932 final int profileIndex
933 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500934
935 int i = 0;
936 int curX = 0;
937 int curY = 0;
938
939 final LauncherAppState app = LauncherAppState.getInstance();
940 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
941 final int width = (int) grid.numColumns;
942 final int height = (int) grid.numRows;
943 final int hotseatWidth = (int) grid.numHotseatIcons;
944
945 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
946
Adam Cohen72960972014-01-15 18:13:55 -0800947 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
948 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500949 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500950
951 while (c.moveToNext()) {
952 final int itemType = c.getInt(itemTypeIndex);
953 if (itemType != Favorites.ITEM_TYPE_APPLICATION
954 && itemType != Favorites.ITEM_TYPE_SHORTCUT
955 && itemType != Favorites.ITEM_TYPE_FOLDER) {
956 continue;
957 }
958
959 final int cellX = c.getInt(cellXIndex);
960 final int cellY = c.getInt(cellYIndex);
961 final int screen = c.getInt(screenIndex);
962 int container = c.getInt(containerIndex);
963 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100964
965 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
966 UserHandleCompat userHandle;
967 final long userSerialNumber;
968 if (profileIndex != -1 && !c.isNull(profileIndex)) {
969 userSerialNumber = c.getInt(profileIndex);
970 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
971 } else {
972 // Default to the serial number of this user, for older
973 // shortcuts.
974 userHandle = UserHandleCompat.myUserHandle();
975 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
976 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800977
978 if (userHandle == null) {
979 Launcher.addDumpLog(TAG, "skipping deleted user", true);
980 continue;
981 }
982
Dan Sandlerd5024042014-01-09 15:01:33 -0500983 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500984 + c.getString(titleIndex) + "\" ("
985 + cellX + "," + cellY + "@"
986 + LauncherSettings.Favorites.containerToString(container)
987 + "/" + screen
988 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500989
990 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800991
992 final Intent intent;
993 final ComponentName cn;
994 try {
995 intent = Intent.parseUri(intentStr, 0);
996 } catch (URISyntaxException e) {
997 // bogus intent?
998 Launcher.addDumpLog(TAG,
999 "skipping invalid intent uri", true);
1000 continue;
1001 }
1002
1003 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001004 if (TextUtils.isEmpty(intentStr)) {
1005 // no intent? no icon
1006 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1007 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001008 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001009 !LauncherModel.isValidPackageActivity(mContext, cn,
1010 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001011 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001012 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001013 "no longer exists.", true);
1014 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001015 } else if (container ==
1016 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1017 // Dedupe icons directly on the workspace
1018
Adam Cohen556f6132014-01-15 15:18:08 -08001019 // Canonicalize
1020 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001021 // does not, so we clear that out to keep them the same.
1022 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001023 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001024 int flags = intent.getFlags();
1025 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001026 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001027 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001028 if (seenIntents.contains(key)) {
1029 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001030 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001031 } else {
1032 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001033 }
1034 }
1035 }
1036
1037 ContentValues values = new ContentValues(c.getColumnCount());
1038 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1039 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1040 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1041 values.put(LauncherSettings.Favorites.ICON_TYPE,
1042 c.getInt(iconTypeIndex));
1043 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1044 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1045 c.getString(iconPackageIndex));
1046 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1047 c.getString(iconResourceIndex));
1048 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1049 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1050 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1051 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1052 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001053 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001054
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001055 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1056 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001057 }
1058
1059 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1060 // In a folder or in the hotseat, preserve position
1061 values.put(LauncherSettings.Favorites.SCREEN, screen);
1062 values.put(LauncherSettings.Favorites.CELLX, cellX);
1063 values.put(LauncherSettings.Favorites.CELLY, cellY);
1064 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001065 // For items contained directly on one of the workspace screen,
1066 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001067 }
1068
1069 values.put(LauncherSettings.Favorites.CONTAINER, container);
1070
Adam Cohen72960972014-01-15 18:13:55 -08001071 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1072 shortcuts.add(values);
1073 } else {
1074 folders.add(values);
1075 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001076 }
1077
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001078 // Now that we have all the hotseat icons, let's go through them left-right
1079 // and assign valid locations for them in the new hotseat
1080 final int N = hotseat.size();
1081 for (int idx=0; idx<N; idx++) {
1082 int hotseatX = hotseat.keyAt(idx);
1083 ContentValues values = hotseat.valueAt(idx);
1084
1085 if (hotseatX == grid.hotseatAllAppsRank) {
1086 // let's drop this in the next available hole in the hotseat
1087 while (++hotseatX < hotseatWidth) {
1088 if (hotseat.get(hotseatX) == null) {
1089 // found a spot! move it here
1090 values.put(LauncherSettings.Favorites.SCREEN,
1091 hotseatX);
1092 break;
1093 }
1094 }
1095 }
1096 if (hotseatX >= hotseatWidth) {
1097 // no room for you in the hotseat? it's off to the desktop with you
1098 values.put(LauncherSettings.Favorites.CONTAINER,
1099 Favorites.CONTAINER_DESKTOP);
1100 }
1101 }
1102
Adam Cohen72960972014-01-15 18:13:55 -08001103 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1104 // Folders first
1105 allItems.addAll(folders);
1106 // Then shortcuts
1107 allItems.addAll(shortcuts);
1108
1109 // Layout all the folders
1110 for (ContentValues values: allItems) {
1111 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1112 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1113 // Hotseat items and folder items have already had their
1114 // location information set. Nothing to be done here.
1115 continue;
1116 }
1117 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1118 values.put(LauncherSettings.Favorites.CELLX, curX);
1119 values.put(LauncherSettings.Favorites.CELLY, curY);
1120 curX = (curX + 1) % width;
1121 if (curX == 0) {
1122 curY = (curY + 1);
1123 }
1124 // Leave the last row of icons blank on every screen
1125 if (curY == height - 1) {
1126 curScreen = (int) generateNewScreenId();
1127 curY = 0;
1128 }
1129 }
1130
1131 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001132 db.beginTransaction();
1133 try {
Adam Cohen72960972014-01-15 18:13:55 -08001134 for (ContentValues row: allItems) {
1135 if (row == null) continue;
1136 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001137 < 0) {
1138 return;
1139 } else {
1140 count++;
1141 }
1142 }
1143 db.setTransactionSuccessful();
1144 } finally {
1145 db.endTransaction();
1146 }
1147 }
1148
1149 db.beginTransaction();
1150 try {
1151 for (i=0; i<=curScreen; i++) {
1152 final ContentValues values = new ContentValues();
1153 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1154 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1155 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1156 < 0) {
1157 return;
1158 }
1159 }
1160 db.setTransactionSuccessful();
1161 } finally {
1162 db.endTransaction();
1163 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001164
1165 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001166 }
1167 } finally {
1168 c.close();
1169 }
1170 }
1171
1172 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1173 + (curScreen+1) + " screens", true);
1174
1175 // ensure that new screens are created to hold these icons
1176 setFlagJustLoadedOldDb();
1177
1178 // Update max IDs; very important since we just grabbed IDs from another database
1179 mMaxItemId = initializeMaxItemId(db);
1180 mMaxScreenId = initializeMaxScreenId(db);
1181 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1182 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001183 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001184
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001185 static class SqlArguments {
1186 public final String table;
1187 public final String where;
1188 public final String[] args;
1189
1190 SqlArguments(Uri url, String where, String[] args) {
1191 if (url.getPathSegments().size() == 1) {
1192 this.table = url.getPathSegments().get(0);
1193 this.where = where;
1194 this.args = args;
1195 } else if (url.getPathSegments().size() != 2) {
1196 throw new IllegalArgumentException("Invalid URI: " + url);
1197 } else if (!TextUtils.isEmpty(where)) {
1198 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1199 } else {
1200 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001201 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001202 this.args = null;
1203 }
1204 }
1205
1206 SqlArguments(Uri url) {
1207 if (url.getPathSegments().size() == 1) {
1208 table = url.getPathSegments().get(0);
1209 where = null;
1210 args = null;
1211 } else {
1212 throw new IllegalArgumentException("Invalid URI: " + url);
1213 }
1214 }
1215 }
Adam Cohen72960972014-01-15 18:13:55 -08001216}