blob: 0088f26cf20b27940abc77753327c9d9994b1101 [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 Agrawala258f812015-01-26 14:07:29 -080089 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
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()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800641 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
642 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800643 new Object[] {c.getLong(1) + 1, c.getLong(0)});
644 }
645
646 c.close();
647 db.setTransactionSuccessful();
648 } catch (SQLException ex) {
649 // Old version remains, which means we wipe old data
650 Log.e(TAG, ex.getMessage(), ex);
651 return false;
652 } finally {
653 db.endTransaction();
654 }
655 return true;
656 }
657
Kenny Guyed131872014-04-30 03:02:21 +0100658 private boolean addProfileColumn(SQLiteDatabase db) {
659 db.beginTransaction();
660 try {
661 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
662 // Default to the serial number of this user, for older
663 // shortcuts.
664 long userSerialNumber = userManager.getSerialNumberForUser(
665 UserHandleCompat.myUserHandle());
666 // Insert new column for holding user serial number
667 db.execSQL("ALTER TABLE favorites " +
668 "ADD COLUMN profileId INTEGER DEFAULT "
669 + userSerialNumber + ";");
670 db.setTransactionSuccessful();
671 } catch (SQLException ex) {
672 // Old version remains, which means we wipe old data
673 Log.e(TAG, ex.getMessage(), ex);
674 return false;
675 } finally {
676 db.endTransaction();
677 }
678 return true;
679 }
680
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700681 // Generates a new ID to use for an object in your database. This method should be only
682 // called from the main UI thread. As an exception, we do call it when we call the
683 // constructor from the worker thread; however, this doesn't extend until after the
684 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
685 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700686 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700687 public long generateNewItemId() {
688 if (mMaxItemId < 0) {
689 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700690 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700691 mMaxItemId += 1;
692 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700693 }
694
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700695 @Override
696 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
697 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
698 }
699
Winson Chungc763c4e2013-07-19 13:49:06 -0700700 public void updateMaxItemId(long id) {
701 mMaxItemId = id + 1;
702 }
703
Chris Wren5dee7af2013-12-20 17:22:11 -0500704 public void checkId(String table, ContentValues values) {
705 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
706 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
707 mMaxScreenId = Math.max(id, mMaxScreenId);
708 } else {
709 mMaxItemId = Math.max(id, mMaxItemId);
710 }
711 }
712
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700714 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
715
716 // get the result
717 final int maxIdIndex = 0;
718 long id = -1;
719 if (c != null && c.moveToNext()) {
720 id = c.getLong(maxIdIndex);
721 }
Michael Jurka5130e402011-10-13 04:55:35 -0700722 if (c != null) {
723 c.close();
724 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700725
726 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700727 throw new RuntimeException("Error: could not query max item id");
728 }
729
730 return id;
731 }
732
733 // Generates a new ID to use for an workspace screen in your database. This method
734 // should be only called from the main UI thread. As an exception, we do call it when we
735 // call the constructor from the worker thread; however, this doesn't extend until after the
736 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
737 // after that point
738 public long generateNewScreenId() {
739 if (mMaxScreenId < 0) {
740 throw new RuntimeException("Error: max screen id was not initialized");
741 }
742 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800743 // Log to disk
744 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700745 return mMaxScreenId;
746 }
747
748 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800749 // Log to disk
750 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 mMaxScreenId = maxScreenId;
752 }
753
754 private long initializeMaxScreenId(SQLiteDatabase db) {
755 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
756
757 // get the result
758 final int maxIdIndex = 0;
759 long id = -1;
760 if (c != null && c.moveToNext()) {
761 id = c.getLong(maxIdIndex);
762 }
763 if (c != null) {
764 c.close();
765 }
766
767 if (id == -1) {
768 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700769 }
770
Winson Chunga90303b2013-11-15 13:05:06 -0800771 // Log to disk
772 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700773 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800774 }
775
Adam Cohena043fa82014-07-23 14:49:38 -0700776 private boolean initializeExternalAdd(ContentValues values) {
777 // 1. Ensure that externally added items have a valid item id
778 long id = generateNewItemId();
779 values.put(LauncherSettings.Favorites._ID, id);
780
781 // 2. In the case of an app widget, and if no app widget id is specified, we
782 // attempt allocate and bind the widget.
783 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
784 if (itemType != null &&
785 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
786 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
787
788 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
789 ComponentName cn = ComponentName.unflattenFromString(
790 values.getAsString(Favorites.APPWIDGET_PROVIDER));
791
792 if (cn != null) {
793 try {
794 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700795 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700796 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700797 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700798 }
799 } catch (RuntimeException e) {
800 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700801 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700802 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700803 } else {
804 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700805 }
806 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700807
808 // Add screen id if not present
809 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
810 if (!addScreenIdIfNecessary(screenId)) {
811 return false;
812 }
Adam Cohena043fa82014-07-23 14:49:38 -0700813 return true;
814 }
815
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700816 // Returns true of screen id exists, or if successfully added
817 private boolean addScreenIdIfNecessary(long screenId) {
818 if (!hasScreenId(screenId)) {
819 int rank = getMaxScreenRank() + 1;
820
821 ContentValues v = new ContentValues();
822 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
823 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
824 if (dbInsertAndCheck(this, getWritableDatabase(),
825 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
826 return false;
827 }
828 }
829 return true;
830 }
831
832 private boolean hasScreenId(long screenId) {
833 SQLiteDatabase db = getWritableDatabase();
834 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
835 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
836 if (c != null) {
837 int count = c.getCount();
838 c.close();
839 return count > 0;
840 } else {
841 return false;
842 }
843 }
844
845 private int getMaxScreenRank() {
846 SQLiteDatabase db = getWritableDatabase();
847 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
848 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
849
850 // get the result
851 final int maxRankIndex = 0;
852 int rank = -1;
853 if (c != null && c.moveToNext()) {
854 rank = c.getInt(maxRankIndex);
855 }
856 if (c != null) {
857 c.close();
858 }
859
860 return rank;
861 }
862
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700863 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700864 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700865 // TODO: Use multiple loaders with fall-back and transaction.
866 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700867
868 // Add the screens specified by the items above
869 Collections.sort(screenIds);
870 int rank = 0;
871 ContentValues values = new ContentValues();
872 for (Long id : screenIds) {
873 values.clear();
874 values.put(LauncherSettings.WorkspaceScreens._ID, id);
875 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
876 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
877 throw new RuntimeException("Failed initialize screen table"
878 + "from default layout");
879 }
880 rank++;
881 }
882
883 // Ensure that the max ids are initialized
884 mMaxItemId = initializeMaxItemId(db);
885 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700886
Adam Cohen71483f42014-05-15 14:04:01 -0700887 return count;
888 }
889
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700890 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500891 final ContentResolver resolver = mContext.getContentResolver();
892 Cursor c = null;
893 int count = 0;
894 int curScreen = 0;
895
896 try {
897 c = resolver.query(uri, null, null, null, "title ASC");
898 } catch (Exception e) {
899 // Ignore
900 }
901
Dan Sandlerd5024042014-01-09 15:01:33 -0500902 // We already have a favorites database in the old provider
903 if (c != null) {
904 try {
905 if (c.getCount() > 0) {
906 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
907 final int intentIndex
908 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
909 final int titleIndex
910 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
911 final int iconTypeIndex
912 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
913 final int iconIndex
914 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
915 final int iconPackageIndex
916 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
917 final int iconResourceIndex
918 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
919 final int containerIndex
920 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
921 final int itemTypeIndex
922 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
923 final int screenIndex
924 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
925 final int cellXIndex
926 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
927 final int cellYIndex
928 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
929 final int uriIndex
930 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
931 final int displayModeIndex
932 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100933 final int profileIndex
934 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500935
936 int i = 0;
937 int curX = 0;
938 int curY = 0;
939
940 final LauncherAppState app = LauncherAppState.getInstance();
941 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
942 final int width = (int) grid.numColumns;
943 final int height = (int) grid.numRows;
944 final int hotseatWidth = (int) grid.numHotseatIcons;
945
946 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
947
Adam Cohen72960972014-01-15 18:13:55 -0800948 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
949 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500950 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500951
952 while (c.moveToNext()) {
953 final int itemType = c.getInt(itemTypeIndex);
954 if (itemType != Favorites.ITEM_TYPE_APPLICATION
955 && itemType != Favorites.ITEM_TYPE_SHORTCUT
956 && itemType != Favorites.ITEM_TYPE_FOLDER) {
957 continue;
958 }
959
960 final int cellX = c.getInt(cellXIndex);
961 final int cellY = c.getInt(cellYIndex);
962 final int screen = c.getInt(screenIndex);
963 int container = c.getInt(containerIndex);
964 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100965
966 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
967 UserHandleCompat userHandle;
968 final long userSerialNumber;
969 if (profileIndex != -1 && !c.isNull(profileIndex)) {
970 userSerialNumber = c.getInt(profileIndex);
971 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
972 } else {
973 // Default to the serial number of this user, for older
974 // shortcuts.
975 userHandle = UserHandleCompat.myUserHandle();
976 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
977 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800978
979 if (userHandle == null) {
980 Launcher.addDumpLog(TAG, "skipping deleted user", true);
981 continue;
982 }
983
Dan Sandlerd5024042014-01-09 15:01:33 -0500984 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500985 + c.getString(titleIndex) + "\" ("
986 + cellX + "," + cellY + "@"
987 + LauncherSettings.Favorites.containerToString(container)
988 + "/" + screen
989 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500990
991 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800992
993 final Intent intent;
994 final ComponentName cn;
995 try {
996 intent = Intent.parseUri(intentStr, 0);
997 } catch (URISyntaxException e) {
998 // bogus intent?
999 Launcher.addDumpLog(TAG,
1000 "skipping invalid intent uri", true);
1001 continue;
1002 }
1003
1004 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001005 if (TextUtils.isEmpty(intentStr)) {
1006 // no intent? no icon
1007 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1008 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001009 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001010 !LauncherModel.isValidPackageActivity(mContext, cn,
1011 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001012 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001013 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001014 "no longer exists.", true);
1015 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001016 } else if (container ==
1017 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1018 // Dedupe icons directly on the workspace
1019
Adam Cohen556f6132014-01-15 15:18:08 -08001020 // Canonicalize
1021 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001022 // does not, so we clear that out to keep them the same.
1023 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001024 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001025 int flags = intent.getFlags();
1026 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001027 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001028 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001029 if (seenIntents.contains(key)) {
1030 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001031 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001032 } else {
1033 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001034 }
1035 }
1036 }
1037
1038 ContentValues values = new ContentValues(c.getColumnCount());
1039 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1040 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1041 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1042 values.put(LauncherSettings.Favorites.ICON_TYPE,
1043 c.getInt(iconTypeIndex));
1044 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1045 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1046 c.getString(iconPackageIndex));
1047 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1048 c.getString(iconResourceIndex));
1049 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1050 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1051 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1052 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1053 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001054 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001055
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001056 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1057 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001058 }
1059
1060 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1061 // In a folder or in the hotseat, preserve position
1062 values.put(LauncherSettings.Favorites.SCREEN, screen);
1063 values.put(LauncherSettings.Favorites.CELLX, cellX);
1064 values.put(LauncherSettings.Favorites.CELLY, cellY);
1065 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001066 // For items contained directly on one of the workspace screen,
1067 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001068 }
1069
1070 values.put(LauncherSettings.Favorites.CONTAINER, container);
1071
Adam Cohen72960972014-01-15 18:13:55 -08001072 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1073 shortcuts.add(values);
1074 } else {
1075 folders.add(values);
1076 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001077 }
1078
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001079 // Now that we have all the hotseat icons, let's go through them left-right
1080 // and assign valid locations for them in the new hotseat
1081 final int N = hotseat.size();
1082 for (int idx=0; idx<N; idx++) {
1083 int hotseatX = hotseat.keyAt(idx);
1084 ContentValues values = hotseat.valueAt(idx);
1085
1086 if (hotseatX == grid.hotseatAllAppsRank) {
1087 // let's drop this in the next available hole in the hotseat
1088 while (++hotseatX < hotseatWidth) {
1089 if (hotseat.get(hotseatX) == null) {
1090 // found a spot! move it here
1091 values.put(LauncherSettings.Favorites.SCREEN,
1092 hotseatX);
1093 break;
1094 }
1095 }
1096 }
1097 if (hotseatX >= hotseatWidth) {
1098 // no room for you in the hotseat? it's off to the desktop with you
1099 values.put(LauncherSettings.Favorites.CONTAINER,
1100 Favorites.CONTAINER_DESKTOP);
1101 }
1102 }
1103
Adam Cohen72960972014-01-15 18:13:55 -08001104 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1105 // Folders first
1106 allItems.addAll(folders);
1107 // Then shortcuts
1108 allItems.addAll(shortcuts);
1109
1110 // Layout all the folders
1111 for (ContentValues values: allItems) {
1112 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1113 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1114 // Hotseat items and folder items have already had their
1115 // location information set. Nothing to be done here.
1116 continue;
1117 }
1118 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1119 values.put(LauncherSettings.Favorites.CELLX, curX);
1120 values.put(LauncherSettings.Favorites.CELLY, curY);
1121 curX = (curX + 1) % width;
1122 if (curX == 0) {
1123 curY = (curY + 1);
1124 }
1125 // Leave the last row of icons blank on every screen
1126 if (curY == height - 1) {
1127 curScreen = (int) generateNewScreenId();
1128 curY = 0;
1129 }
1130 }
1131
1132 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001133 db.beginTransaction();
1134 try {
Adam Cohen72960972014-01-15 18:13:55 -08001135 for (ContentValues row: allItems) {
1136 if (row == null) continue;
1137 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001138 < 0) {
1139 return;
1140 } else {
1141 count++;
1142 }
1143 }
1144 db.setTransactionSuccessful();
1145 } finally {
1146 db.endTransaction();
1147 }
1148 }
1149
1150 db.beginTransaction();
1151 try {
1152 for (i=0; i<=curScreen; i++) {
1153 final ContentValues values = new ContentValues();
1154 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1155 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1156 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1157 < 0) {
1158 return;
1159 }
1160 }
1161 db.setTransactionSuccessful();
1162 } finally {
1163 db.endTransaction();
1164 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001165
1166 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001167 }
1168 } finally {
1169 c.close();
1170 }
1171 }
1172
1173 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1174 + (curScreen+1) + " screens", true);
1175
1176 // ensure that new screens are created to hold these icons
1177 setFlagJustLoadedOldDb();
1178
1179 // Update max IDs; very important since we just grabbed IDs from another database
1180 mMaxItemId = initializeMaxItemId(db);
1181 mMaxScreenId = initializeMaxScreenId(db);
1182 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1183 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001184 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001185
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001186 static class SqlArguments {
1187 public final String table;
1188 public final String where;
1189 public final String[] args;
1190
1191 SqlArguments(Uri url, String where, String[] args) {
1192 if (url.getPathSegments().size() == 1) {
1193 this.table = url.getPathSegments().get(0);
1194 this.where = where;
1195 this.args = args;
1196 } else if (url.getPathSegments().size() != 2) {
1197 throw new IllegalArgumentException("Invalid URI: " + url);
1198 } else if (!TextUtils.isEmpty(where)) {
1199 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1200 } else {
1201 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001202 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001203 this.args = null;
1204 }
1205 }
1206
1207 SqlArguments(Uri url) {
1208 if (url.getPathSegments().size() == 1) {
1209 table = url.getPathSegments().get(0);
1210 where = null;
1211 args = null;
1212 } else {
1213 throw new IllegalArgumentException("Invalid URI: " + url);
1214 }
1215 }
1216 }
Adam Cohen72960972014-01-15 18:13:55 -08001217}