blob: 196f57c3cb099c7c25b7ef9f96cf3d17d6c21f7d [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 Goyal08f72612015-01-05 13:41:43 -080060 private static final int DATABASE_VERSION = 21;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061
Adam Cohene25af792013-06-06 23:08:25 -070062 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040063 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070066 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080068 static final String UPGRADED_FROM_OLD_DATABASE = "UPGRADED_FROM_OLD_DATABASE";
69 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Adam Cohena043fa82014-07-23 14:49:38 -070071 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
72
Anjali Koppal67e7cae2014-03-13 12:14:12 -070073 private LauncherProviderChangeListener mListener;
74
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070075 /**
Romain Guy73b979d2009-06-09 12:57:21 -070076 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070077 * {@link AppWidgetHost#deleteHost()} is called during database creation.
78 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
79 */
80 static final Uri CONTENT_APPWIDGET_RESET_URI =
81 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070082
Michael Jurkaa8c760d2011-04-28 14:59:33 -070083 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
85 @Override
86 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040087 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080088 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040089 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080090 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 return true;
93 }
94
Winson Chung0b560dd2014-01-21 13:00:26 -080095 public boolean wasNewDbCreated() {
96 return mOpenHelper.wasNewDbCreated();
97 }
98
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
100 mListener = listener;
101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public String getType(Uri uri) {
105 SqlArguments args = new SqlArguments(uri, null, null);
106 if (TextUtils.isEmpty(args.where)) {
107 return "vnd.android.cursor.dir/" + args.table;
108 } else {
109 return "vnd.android.cursor.item/" + args.table;
110 }
111 }
112
113 @Override
114 public Cursor query(Uri uri, String[] projection, String selection,
115 String[] selectionArgs, String sortOrder) {
116
117 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
118 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
119 qb.setTables(args.table);
120
Romain Guy73b979d2009-06-09 12:57:21 -0700121 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
123 result.setNotificationUri(getContext().getContentResolver(), uri);
124
125 return result;
126 }
127
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700128 private static long dbInsertAndCheck(DatabaseHelper helper,
129 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500130 if (values == null) {
131 throw new RuntimeException("Error: attempting to insert null values");
132 }
Adam Cohen71483f42014-05-15 14:04:01 -0700133 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 throw new RuntimeException("Error: attempting to add item without specifying an id");
135 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500136 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 return db.insert(table, nullColumnHack, values);
138 }
139
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140 @Override
141 public Uri insert(Uri uri, ContentValues initialValues) {
142 SqlArguments args = new SqlArguments(uri);
143
Adam Cohena043fa82014-07-23 14:49:38 -0700144 // In very limited cases, we support system|signature permission apps to add to the db
145 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
146 if (externalAdd != null && "true".equals(externalAdd)) {
147 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
148 return null;
149 }
150 }
151
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400153 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 if (rowId <= 0) return null;
156
157 uri = ContentUris.withAppendedId(uri, rowId);
158 sendNotify(uri);
159
160 return uri;
161 }
162
Adam Cohena043fa82014-07-23 14:49:38 -0700163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 @Override
165 public int bulkInsert(Uri uri, ContentValues[] values) {
166 SqlArguments args = new SqlArguments(uri);
167
168 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
169 db.beginTransaction();
170 try {
171 int numValues = values.length;
172 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
175 return 0;
176 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177 }
178 db.setTransactionSuccessful();
179 } finally {
180 db.endTransaction();
181 }
182
183 sendNotify(uri);
184 return values.length;
185 }
186
187 @Override
Yura085c8532014-02-11 15:15:29 +0000188 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
189 throws OperationApplicationException {
190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
191 db.beginTransaction();
192 try {
193 ContentProviderResult[] result = super.applyBatch(operations);
194 db.setTransactionSuccessful();
195 return result;
196 } finally {
197 db.endTransaction();
198 }
199 }
200
201 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 public int delete(Uri uri, String selection, String[] selectionArgs) {
203 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
204
205 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
206 int count = db.delete(args.table, args.where, args.args);
207 if (count > 0) sendNotify(uri);
208
209 return count;
210 }
211
212 @Override
213 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
214 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
215
Chris Wren1ada10d2013-09-13 18:01:38 -0400216 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
218 int count = db.update(args.table, values, args.where, args.args);
219 if (count > 0) sendNotify(uri);
220
221 return count;
222 }
223
224 private void sendNotify(Uri uri) {
225 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
226 if (notify == null || "true".equals(notify)) {
227 getContext().getContentResolver().notifyChange(uri, null);
228 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400229
230 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400231 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700232 if (mListener != null) {
233 mListener.onLauncherProviderChange();
234 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400235 }
236
237 private void addModifiedTime(ContentValues values) {
238 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239 }
240
Adam Cohendcd297f2013-06-18 13:13:40 -0700241 public long generateNewItemId() {
242 return mOpenHelper.generateNewItemId();
243 }
244
Winson Chungc763c4e2013-07-19 13:49:06 -0700245 public void updateMaxItemId(long id) {
246 mOpenHelper.updateMaxItemId(id);
247 }
248
Adam Cohendcd297f2013-06-18 13:13:40 -0700249 public long generateNewScreenId() {
250 return mOpenHelper.generateNewScreenId();
251 }
252
253 // This is only required one time while loading the workspace during the
254 // upgrade path, and should never be called from anywhere else.
255 public void updateMaxScreenId(long maxScreenId) {
256 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700257 }
258
Brian Muramatsu5524b492012-10-02 16:55:54 -0700259 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700260 * Clears all the data for a fresh start.
261 */
262 synchronized public void createEmptyDB() {
263 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
264 }
265
Sunny Goyal33d44382014-10-16 09:24:19 -0700266 public void clearFlagEmptyDbCreated() {
267 String spKey = LauncherAppState.getSharedPreferencesKey();
268 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
269 .edit()
270 .remove(EMPTY_DATABASE_CREATED)
271 .commit();
272 }
273
Sunny Goyal42de82f2014-09-26 22:09:29 -0700274 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700275 * Loads the default workspace based on the following priority scheme:
276 * 1) From a package provided by play store
277 * 2) From a partner configuration APK, already in the system image
278 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700279 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700280 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400281 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700282 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700283
Winson Chungc763c4e2013-07-19 13:49:06 -0700284 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500285 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200286
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700287 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700288 mOpenHelper.mAppWidgetHost, mOpenHelper);
289
290 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700291 final Partner partner = Partner.get(getContext().getPackageManager());
292 if (partner != null && partner.hasDefaultLayout()) {
293 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700294 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700295 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700296 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700297 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
298 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700299 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700300 }
301 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700302
Sunny Goyal9d219682014-10-23 14:21:02 -0700303 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700304 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700305 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700306 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700307 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700308 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
309 && usingExternallyProvidedLayout) {
310 // Unable to load external layout. Cleanup and load the internal layout.
311 createEmptyDB();
312 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
313 getDefaultLayoutParser());
314 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700315 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700316 }
317 }
318
Sunny Goyal9d219682014-10-23 14:21:02 -0700319 private DefaultLayoutParser getDefaultLayoutParser() {
320 int defaultLayout = LauncherAppState.getInstance()
321 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
322 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
323 mOpenHelper, getContext().getResources(), defaultLayout);
324 }
325
Dan Sandlerd5024042014-01-09 15:01:33 -0500326 public void migrateLauncher2Shortcuts() {
327 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400328 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500329 }
330
Sunny Goyal08f72612015-01-05 13:41:43 -0800331 public void updateFolderItemsRank() {
332 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
333 }
334
Dan Sandlerd5024042014-01-09 15:01:33 -0500335 public void deleteDatabase() {
336 // Are you sure? (y/n)
337 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500338 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500339 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500340 if (dbFile.exists()) {
341 SQLiteDatabase.deleteDatabase(dbFile);
342 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500343 mOpenHelper = new DatabaseHelper(getContext());
344 }
345
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700346 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700348 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700349 private long mMaxItemId = -1;
350 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351
Winson Chung0b560dd2014-01-21 13:00:26 -0800352 private boolean mNewDbCreated = false;
353
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100355 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700357 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700358
359 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
360 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700361 if (mMaxItemId == -1) {
362 mMaxItemId = initializeMaxItemId(getWritableDatabase());
363 }
364 if (mMaxScreenId == -1) {
365 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700366 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 }
368
Winson Chung0b560dd2014-01-21 13:00:26 -0800369 public boolean wasNewDbCreated() {
370 return mNewDbCreated;
371 }
372
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700373 /**
374 * Send notification that we've deleted the {@link AppWidgetHost},
375 * probably as part of the initial database creation. The receiver may
376 * want to re-call {@link AppWidgetHost#startListening()} to ensure
377 * callbacks are correctly set.
378 */
379 private void sendAppWidgetResetNotify() {
380 final ContentResolver resolver = mContext.getContentResolver();
381 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
382 }
383
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800384 @Override
385 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800386 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700387
Adam Cohendcd297f2013-06-18 13:13:40 -0700388 mMaxItemId = 1;
389 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800390 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700391
Kenny Guyed131872014-04-30 03:02:21 +0100392 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
393 long userSerialNumber = userManager.getSerialNumberForUser(
394 UserHandleCompat.myUserHandle());
395
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800396 db.execSQL("CREATE TABLE favorites (" +
397 "_id INTEGER PRIMARY KEY," +
398 "title TEXT," +
399 "intent TEXT," +
400 "container INTEGER," +
401 "screen INTEGER," +
402 "cellX INTEGER," +
403 "cellY INTEGER," +
404 "spanX INTEGER," +
405 "spanY INTEGER," +
406 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700407 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800408 "isShortcut INTEGER," +
409 "iconType INTEGER," +
410 "iconPackage TEXT," +
411 "iconResource TEXT," +
412 "icon BLOB," +
413 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400414 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400415 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500416 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100417 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800418 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
419 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800420 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700421 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800422
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700423 // Database was just created, so wipe any previous widgets
424 if (mAppWidgetHost != null) {
425 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700426 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800427 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700428
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800429 // Fresh and clean launcher DB.
430 mMaxItemId = initializeMaxItemId(db);
431 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800432 }
433
Adam Cohendcd297f2013-06-18 13:13:40 -0700434 private void addWorkspacesTable(SQLiteDatabase db) {
435 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
436 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
438 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700439 ");");
440 }
441
Adam Cohen119285e2014-04-02 16:59:08 -0700442 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700443 // Delete items directly on the workspace who's screen id doesn't exist
444 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
445 // AND container = -100"
446 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
447 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700448 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700449 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
450 " AND " +
451 LauncherSettings.Favorites.CONTAINER + " = " +
452 LauncherSettings.Favorites.CONTAINER_DESKTOP;
453 db.execSQL(removeOrphanedDesktopItems);
454
455 // Delete items contained in folders which no longer exist (after above statement)
456 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
457 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
458 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
459 " WHERE " +
460 LauncherSettings.Favorites.CONTAINER + " <> " +
461 LauncherSettings.Favorites.CONTAINER_DESKTOP +
462 " AND "
463 + LauncherSettings.Favorites.CONTAINER + " <> " +
464 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
465 " AND "
466 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
467 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
468 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
469 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
470 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700471 }
472
Winson Chungc763c4e2013-07-19 13:49:06 -0700473 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400474 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700475 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
476 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700477 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
478 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700479 editor.commit();
480 }
481
Winson Chungc763c4e2013-07-19 13:49:06 -0700482 private void setFlagEmptyDbCreated() {
483 String spKey = LauncherAppState.getSharedPreferencesKey();
484 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
485 SharedPreferences.Editor editor = sp.edit();
486 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
487 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
488 editor.commit();
489 }
490
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800491 @Override
492 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700493 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800494 switch (oldVersion) {
495 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800496 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800497 case 12: {
498 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
499 // to persist workspace screens and their relative order.
500 mMaxScreenId = 0;
501 addWorkspacesTable(db);
502 }
503 case 13: {
504 db.beginTransaction();
505 try {
506 // Insert new column for holding widget provider name
507 db.execSQL("ALTER TABLE favorites " +
508 "ADD COLUMN appWidgetProvider TEXT;");
509 db.setTransactionSuccessful();
510 } catch (SQLException ex) {
511 Log.e(TAG, ex.getMessage(), ex);
512 // Old version remains, which means we wipe old data
513 break;
514 } finally {
515 db.endTransaction();
516 }
517 }
518 case 14: {
519 db.beginTransaction();
520 try {
521 // Insert new column for holding update timestamp
522 db.execSQL("ALTER TABLE favorites " +
523 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
524 db.execSQL("ALTER TABLE workspaceScreens " +
525 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
526 db.setTransactionSuccessful();
527 } catch (SQLException ex) {
528 Log.e(TAG, ex.getMessage(), ex);
529 // Old version remains, which means we wipe old data
530 break;
531 } finally {
532 db.endTransaction();
533 }
534 }
535 case 15: {
536 db.beginTransaction();
537 try {
538 // Insert new column for holding restore status
539 db.execSQL("ALTER TABLE favorites " +
540 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
541 db.setTransactionSuccessful();
542 } catch (SQLException ex) {
543 Log.e(TAG, ex.getMessage(), ex);
544 // Old version remains, which means we wipe old data
545 break;
546 } finally {
547 db.endTransaction();
548 }
549 }
550 case 16: {
551 // We use the db version upgrade here to identify users who may not have seen
552 // clings yet (because they weren't available), but for whom the clings are now
553 // available (tablet users). Because one of the possible cling flows (migration)
554 // is very destructive (wipes out workspaces), we want to prevent this from showing
555 // until clear data. We do so by marking that the clings have been shown.
556 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
557 }
558 case 17: {
559 // No-op
560 }
561 case 18: {
562 // Due to a data loss bug, some users may have items associated with screen ids
563 // which no longer exist. Since this can cause other problems, and since the user
564 // will never see these items anyway, we use database upgrade as an opportunity to
565 // clean things up.
566 removeOrphanedItems(db);
567 }
568 case 19: {
569 // Add userId column
570 if (!addProfileColumn(db)) {
571 // Old version remains, which means we wipe old data
572 break;
573 }
574 }
575 case 20:
576 if (!updateFolderItemsRank(db, true)) {
577 break;
578 }
579 case 21: {
580 // DB Upgraded successfully
581 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400582 }
583 }
584
Sunny Goyala2cc6242015-01-14 14:23:02 -0800585 // DB was not upgraded
586 Log.w(TAG, "Destroying all old data.");
587 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800588 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800589
Adam Cohen9b1d0622014-05-21 19:01:57 -0700590 @Override
591 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
592 // This shouldn't happen -- throw our hands up in the air and start over.
593 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
594 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700595 createEmptyDB(db);
596 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700597
Sunny Goyal42de82f2014-09-26 22:09:29 -0700598
599 /**
600 * Clears all the data for a fresh start.
601 */
602 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700603 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
604 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
605 onCreate(db);
606 }
607
Sunny Goyal08f72612015-01-05 13:41:43 -0800608 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
609 db.beginTransaction();
610 try {
611 if (addRankColumn) {
612 // Insert new column for holding rank
613 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
614 }
615
616 // Get a map for folder ID to folder width
617 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
618 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
619 + " GROUP BY container;",
620 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
621
622 while (c.moveToNext()) {
623 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE container=?;",
624 new Object[] {c.getLong(1) + 1, c.getLong(0)});
625 }
626
627 c.close();
628 db.setTransactionSuccessful();
629 } catch (SQLException ex) {
630 // Old version remains, which means we wipe old data
631 Log.e(TAG, ex.getMessage(), ex);
632 return false;
633 } finally {
634 db.endTransaction();
635 }
636 return true;
637 }
638
Kenny Guyed131872014-04-30 03:02:21 +0100639 private boolean addProfileColumn(SQLiteDatabase db) {
640 db.beginTransaction();
641 try {
642 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
643 // Default to the serial number of this user, for older
644 // shortcuts.
645 long userSerialNumber = userManager.getSerialNumberForUser(
646 UserHandleCompat.myUserHandle());
647 // Insert new column for holding user serial number
648 db.execSQL("ALTER TABLE favorites " +
649 "ADD COLUMN profileId INTEGER DEFAULT "
650 + userSerialNumber + ";");
651 db.setTransactionSuccessful();
652 } catch (SQLException ex) {
653 // Old version remains, which means we wipe old data
654 Log.e(TAG, ex.getMessage(), ex);
655 return false;
656 } finally {
657 db.endTransaction();
658 }
659 return true;
660 }
661
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700662 // Generates a new ID to use for an object in your database. This method should be only
663 // called from the main UI thread. As an exception, we do call it when we call the
664 // constructor from the worker thread; however, this doesn't extend until after the
665 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
666 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700667 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700668 public long generateNewItemId() {
669 if (mMaxItemId < 0) {
670 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700671 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700672 mMaxItemId += 1;
673 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700674 }
675
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700676 @Override
677 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
678 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
679 }
680
Winson Chungc763c4e2013-07-19 13:49:06 -0700681 public void updateMaxItemId(long id) {
682 mMaxItemId = id + 1;
683 }
684
Chris Wren5dee7af2013-12-20 17:22:11 -0500685 public void checkId(String table, ContentValues values) {
686 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
687 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
688 mMaxScreenId = Math.max(id, mMaxScreenId);
689 } else {
690 mMaxItemId = Math.max(id, mMaxItemId);
691 }
692 }
693
Adam Cohendcd297f2013-06-18 13:13:40 -0700694 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700695 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
696
697 // get the result
698 final int maxIdIndex = 0;
699 long id = -1;
700 if (c != null && c.moveToNext()) {
701 id = c.getLong(maxIdIndex);
702 }
Michael Jurka5130e402011-10-13 04:55:35 -0700703 if (c != null) {
704 c.close();
705 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700706
707 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700708 throw new RuntimeException("Error: could not query max item id");
709 }
710
711 return id;
712 }
713
714 // Generates a new ID to use for an workspace screen in your database. This method
715 // should be only called from the main UI thread. As an exception, we do call it when we
716 // call the constructor from the worker thread; however, this doesn't extend until after the
717 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
718 // after that point
719 public long generateNewScreenId() {
720 if (mMaxScreenId < 0) {
721 throw new RuntimeException("Error: max screen id was not initialized");
722 }
723 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800724 // Log to disk
725 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700726 return mMaxScreenId;
727 }
728
729 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800730 // Log to disk
731 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700732 mMaxScreenId = maxScreenId;
733 }
734
735 private long initializeMaxScreenId(SQLiteDatabase db) {
736 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
737
738 // get the result
739 final int maxIdIndex = 0;
740 long id = -1;
741 if (c != null && c.moveToNext()) {
742 id = c.getLong(maxIdIndex);
743 }
744 if (c != null) {
745 c.close();
746 }
747
748 if (id == -1) {
749 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700750 }
751
Winson Chunga90303b2013-11-15 13:05:06 -0800752 // Log to disk
753 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700754 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800755 }
756
Adam Cohena043fa82014-07-23 14:49:38 -0700757 private boolean initializeExternalAdd(ContentValues values) {
758 // 1. Ensure that externally added items have a valid item id
759 long id = generateNewItemId();
760 values.put(LauncherSettings.Favorites._ID, id);
761
762 // 2. In the case of an app widget, and if no app widget id is specified, we
763 // attempt allocate and bind the widget.
764 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
765 if (itemType != null &&
766 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
767 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
768
769 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
770 ComponentName cn = ComponentName.unflattenFromString(
771 values.getAsString(Favorites.APPWIDGET_PROVIDER));
772
773 if (cn != null) {
774 try {
775 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700776 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700777 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700778 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700779 }
780 } catch (RuntimeException e) {
781 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700782 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700783 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700784 } else {
785 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700786 }
787 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700788
789 // Add screen id if not present
790 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
791 if (!addScreenIdIfNecessary(screenId)) {
792 return false;
793 }
Adam Cohena043fa82014-07-23 14:49:38 -0700794 return true;
795 }
796
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700797 // Returns true of screen id exists, or if successfully added
798 private boolean addScreenIdIfNecessary(long screenId) {
799 if (!hasScreenId(screenId)) {
800 int rank = getMaxScreenRank() + 1;
801
802 ContentValues v = new ContentValues();
803 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
804 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
805 if (dbInsertAndCheck(this, getWritableDatabase(),
806 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
807 return false;
808 }
809 }
810 return true;
811 }
812
813 private boolean hasScreenId(long screenId) {
814 SQLiteDatabase db = getWritableDatabase();
815 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
816 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
817 if (c != null) {
818 int count = c.getCount();
819 c.close();
820 return count > 0;
821 } else {
822 return false;
823 }
824 }
825
826 private int getMaxScreenRank() {
827 SQLiteDatabase db = getWritableDatabase();
828 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
829 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
830
831 // get the result
832 final int maxRankIndex = 0;
833 int rank = -1;
834 if (c != null && c.moveToNext()) {
835 rank = c.getInt(maxRankIndex);
836 }
837 if (c != null) {
838 c.close();
839 }
840
841 return rank;
842 }
843
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700844 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700845 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700846 // TODO: Use multiple loaders with fall-back and transaction.
847 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700848
849 // Add the screens specified by the items above
850 Collections.sort(screenIds);
851 int rank = 0;
852 ContentValues values = new ContentValues();
853 for (Long id : screenIds) {
854 values.clear();
855 values.put(LauncherSettings.WorkspaceScreens._ID, id);
856 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
857 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
858 throw new RuntimeException("Failed initialize screen table"
859 + "from default layout");
860 }
861 rank++;
862 }
863
864 // Ensure that the max ids are initialized
865 mMaxItemId = initializeMaxItemId(db);
866 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700867
Adam Cohen71483f42014-05-15 14:04:01 -0700868 return count;
869 }
870
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700871 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500872 final ContentResolver resolver = mContext.getContentResolver();
873 Cursor c = null;
874 int count = 0;
875 int curScreen = 0;
876
877 try {
878 c = resolver.query(uri, null, null, null, "title ASC");
879 } catch (Exception e) {
880 // Ignore
881 }
882
Dan Sandlerd5024042014-01-09 15:01:33 -0500883 // We already have a favorites database in the old provider
884 if (c != null) {
885 try {
886 if (c.getCount() > 0) {
887 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
888 final int intentIndex
889 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
890 final int titleIndex
891 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
892 final int iconTypeIndex
893 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
894 final int iconIndex
895 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
896 final int iconPackageIndex
897 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
898 final int iconResourceIndex
899 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
900 final int containerIndex
901 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
902 final int itemTypeIndex
903 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
904 final int screenIndex
905 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
906 final int cellXIndex
907 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
908 final int cellYIndex
909 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
910 final int uriIndex
911 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
912 final int displayModeIndex
913 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100914 final int profileIndex
915 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500916
917 int i = 0;
918 int curX = 0;
919 int curY = 0;
920
921 final LauncherAppState app = LauncherAppState.getInstance();
922 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
923 final int width = (int) grid.numColumns;
924 final int height = (int) grid.numRows;
925 final int hotseatWidth = (int) grid.numHotseatIcons;
926
927 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
928
Adam Cohen72960972014-01-15 18:13:55 -0800929 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
930 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500931 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500932
933 while (c.moveToNext()) {
934 final int itemType = c.getInt(itemTypeIndex);
935 if (itemType != Favorites.ITEM_TYPE_APPLICATION
936 && itemType != Favorites.ITEM_TYPE_SHORTCUT
937 && itemType != Favorites.ITEM_TYPE_FOLDER) {
938 continue;
939 }
940
941 final int cellX = c.getInt(cellXIndex);
942 final int cellY = c.getInt(cellYIndex);
943 final int screen = c.getInt(screenIndex);
944 int container = c.getInt(containerIndex);
945 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100946
947 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
948 UserHandleCompat userHandle;
949 final long userSerialNumber;
950 if (profileIndex != -1 && !c.isNull(profileIndex)) {
951 userSerialNumber = c.getInt(profileIndex);
952 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
953 } else {
954 // Default to the serial number of this user, for older
955 // shortcuts.
956 userHandle = UserHandleCompat.myUserHandle();
957 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
958 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800959
960 if (userHandle == null) {
961 Launcher.addDumpLog(TAG, "skipping deleted user", true);
962 continue;
963 }
964
Dan Sandlerd5024042014-01-09 15:01:33 -0500965 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500966 + c.getString(titleIndex) + "\" ("
967 + cellX + "," + cellY + "@"
968 + LauncherSettings.Favorites.containerToString(container)
969 + "/" + screen
970 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500971
972 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800973
974 final Intent intent;
975 final ComponentName cn;
976 try {
977 intent = Intent.parseUri(intentStr, 0);
978 } catch (URISyntaxException e) {
979 // bogus intent?
980 Launcher.addDumpLog(TAG,
981 "skipping invalid intent uri", true);
982 continue;
983 }
984
985 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500986 if (TextUtils.isEmpty(intentStr)) {
987 // no intent? no icon
988 Launcher.addDumpLog(TAG, "skipping empty intent", true);
989 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800990 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100991 !LauncherModel.isValidPackageActivity(mContext, cn,
992 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800993 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800994 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -0800995 "no longer exists.", true);
996 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800997 } else if (container ==
998 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
999 // Dedupe icons directly on the workspace
1000
Adam Cohen556f6132014-01-15 15:18:08 -08001001 // Canonicalize
1002 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001003 // does not, so we clear that out to keep them the same.
1004 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001005 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001006 int flags = intent.getFlags();
1007 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001008 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001009 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001010 if (seenIntents.contains(key)) {
1011 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001012 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001013 } else {
1014 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001015 }
1016 }
1017 }
1018
1019 ContentValues values = new ContentValues(c.getColumnCount());
1020 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1021 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1022 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1023 values.put(LauncherSettings.Favorites.ICON_TYPE,
1024 c.getInt(iconTypeIndex));
1025 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1026 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1027 c.getString(iconPackageIndex));
1028 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1029 c.getString(iconResourceIndex));
1030 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1031 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1032 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1033 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1034 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001035 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001036
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001037 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1038 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001039 }
1040
1041 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1042 // In a folder or in the hotseat, preserve position
1043 values.put(LauncherSettings.Favorites.SCREEN, screen);
1044 values.put(LauncherSettings.Favorites.CELLX, cellX);
1045 values.put(LauncherSettings.Favorites.CELLY, cellY);
1046 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001047 // For items contained directly on one of the workspace screen,
1048 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001049 }
1050
1051 values.put(LauncherSettings.Favorites.CONTAINER, container);
1052
Adam Cohen72960972014-01-15 18:13:55 -08001053 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1054 shortcuts.add(values);
1055 } else {
1056 folders.add(values);
1057 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001058 }
1059
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001060 // Now that we have all the hotseat icons, let's go through them left-right
1061 // and assign valid locations for them in the new hotseat
1062 final int N = hotseat.size();
1063 for (int idx=0; idx<N; idx++) {
1064 int hotseatX = hotseat.keyAt(idx);
1065 ContentValues values = hotseat.valueAt(idx);
1066
1067 if (hotseatX == grid.hotseatAllAppsRank) {
1068 // let's drop this in the next available hole in the hotseat
1069 while (++hotseatX < hotseatWidth) {
1070 if (hotseat.get(hotseatX) == null) {
1071 // found a spot! move it here
1072 values.put(LauncherSettings.Favorites.SCREEN,
1073 hotseatX);
1074 break;
1075 }
1076 }
1077 }
1078 if (hotseatX >= hotseatWidth) {
1079 // no room for you in the hotseat? it's off to the desktop with you
1080 values.put(LauncherSettings.Favorites.CONTAINER,
1081 Favorites.CONTAINER_DESKTOP);
1082 }
1083 }
1084
Adam Cohen72960972014-01-15 18:13:55 -08001085 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1086 // Folders first
1087 allItems.addAll(folders);
1088 // Then shortcuts
1089 allItems.addAll(shortcuts);
1090
1091 // Layout all the folders
1092 for (ContentValues values: allItems) {
1093 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1094 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1095 // Hotseat items and folder items have already had their
1096 // location information set. Nothing to be done here.
1097 continue;
1098 }
1099 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1100 values.put(LauncherSettings.Favorites.CELLX, curX);
1101 values.put(LauncherSettings.Favorites.CELLY, curY);
1102 curX = (curX + 1) % width;
1103 if (curX == 0) {
1104 curY = (curY + 1);
1105 }
1106 // Leave the last row of icons blank on every screen
1107 if (curY == height - 1) {
1108 curScreen = (int) generateNewScreenId();
1109 curY = 0;
1110 }
1111 }
1112
1113 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001114 db.beginTransaction();
1115 try {
Adam Cohen72960972014-01-15 18:13:55 -08001116 for (ContentValues row: allItems) {
1117 if (row == null) continue;
1118 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001119 < 0) {
1120 return;
1121 } else {
1122 count++;
1123 }
1124 }
1125 db.setTransactionSuccessful();
1126 } finally {
1127 db.endTransaction();
1128 }
1129 }
1130
1131 db.beginTransaction();
1132 try {
1133 for (i=0; i<=curScreen; i++) {
1134 final ContentValues values = new ContentValues();
1135 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1136 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1137 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1138 < 0) {
1139 return;
1140 }
1141 }
1142 db.setTransactionSuccessful();
1143 } finally {
1144 db.endTransaction();
1145 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001146
1147 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001148 }
1149 } finally {
1150 c.close();
1151 }
1152 }
1153
1154 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1155 + (curScreen+1) + " screens", true);
1156
1157 // ensure that new screens are created to hold these icons
1158 setFlagJustLoadedOldDb();
1159
1160 // Update max IDs; very important since we just grabbed IDs from another database
1161 mMaxItemId = initializeMaxItemId(db);
1162 mMaxScreenId = initializeMaxScreenId(db);
1163 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1164 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001165 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001166
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001167 static class SqlArguments {
1168 public final String table;
1169 public final String where;
1170 public final String[] args;
1171
1172 SqlArguments(Uri url, String where, String[] args) {
1173 if (url.getPathSegments().size() == 1) {
1174 this.table = url.getPathSegments().get(0);
1175 this.where = where;
1176 this.args = args;
1177 } else if (url.getPathSegments().size() != 2) {
1178 throw new IllegalArgumentException("Invalid URI: " + url);
1179 } else if (!TextUtils.isEmpty(where)) {
1180 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1181 } else {
1182 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001183 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001184 this.args = null;
1185 }
1186 }
1187
1188 SqlArguments(Uri url) {
1189 if (url.getPathSegments().size() == 1) {
1190 table = url.getPathSegments().get(0);
1191 where = null;
1192 args = null;
1193 } else {
1194 throw new IllegalArgumentException("Invalid URI: " + url);
1195 }
1196 }
1197 }
Adam Cohen72960972014-01-15 18:13:55 -08001198}