blob: 0272dfd54906b220d9db7b75475b8e59a683beba [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
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000019import android.app.SearchManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000022import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080023import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070024import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000025import android.content.ContentProviderOperation;
26import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000032import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070033import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ActivityInfo;
Jason Monk41314972014-03-03 16:11:30 -050035import android.content.pm.ApplicationInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.content.pm.PackageManager;
Jason Monk41314972014-03-03 16:11:30 -050037import android.content.pm.ResolveInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.content.res.Resources;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.database.Cursor;
41import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070042import android.database.sqlite.SQLiteDatabase;
43import android.database.sqlite.SQLiteOpenHelper;
44import android.database.sqlite.SQLiteQueryBuilder;
45import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080046import android.graphics.Bitmap;
47import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070049import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.provider.Settings;
51import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080052import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050053import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070054
Sunny Goyal0fe505b2014-08-06 09:55:36 -070055import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
56import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010057import com.android.launcher3.compat.UserHandleCompat;
58import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070060
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070068import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050069import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000070import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080073 private static final String TAG = "Launcher.LauncherProvider";
74 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Kenny Guyed131872014-04-30 03:02:21 +010076 private static final int DATABASE_VERSION = 20;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Adam Cohene25af792013-06-06 23:08:25 -070078 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040079 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070080
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050081 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050082 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050083
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070085 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070087 static final String UPGRADED_FROM_OLD_DATABASE =
88 "UPGRADED_FROM_OLD_DATABASE";
89 static final String EMPTY_DATABASE_CREATED =
90 "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Winson Chungb3302ae2012-05-01 10:19:14 -070092 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070093 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070094
Adam Cohena043fa82014-07-23 14:49:38 -070095 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
96
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 private LauncherProviderChangeListener mListener;
98
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070099 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700100 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700101 * {@link AppWidgetHost#deleteHost()} is called during database creation.
102 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
103 */
104 static final Uri CONTENT_APPWIDGET_RESET_URI =
105 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700106
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700107 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700108 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
110 @Override
111 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400112 final Context context = getContext();
113 mOpenHelper = new DatabaseHelper(context);
114 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115 return true;
116 }
117
Winson Chung0b560dd2014-01-21 13:00:26 -0800118 public boolean wasNewDbCreated() {
119 return mOpenHelper.wasNewDbCreated();
120 }
121
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700122 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
123 mListener = listener;
124 }
125
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126 @Override
127 public String getType(Uri uri) {
128 SqlArguments args = new SqlArguments(uri, null, null);
129 if (TextUtils.isEmpty(args.where)) {
130 return "vnd.android.cursor.dir/" + args.table;
131 } else {
132 return "vnd.android.cursor.item/" + args.table;
133 }
134 }
135
136 @Override
137 public Cursor query(Uri uri, String[] projection, String selection,
138 String[] selectionArgs, String sortOrder) {
139
140 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
141 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
142 qb.setTables(args.table);
143
Romain Guy73b979d2009-06-09 12:57:21 -0700144 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
146 result.setNotificationUri(getContext().getContentResolver(), uri);
147
148 return result;
149 }
150
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151 private static long dbInsertAndCheck(DatabaseHelper helper,
152 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500153 if (values == null) {
154 throw new RuntimeException("Error: attempting to insert null values");
155 }
Adam Cohen71483f42014-05-15 14:04:01 -0700156 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 throw new RuntimeException("Error: attempting to add item without specifying an id");
158 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500159 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 return db.insert(table, nullColumnHack, values);
161 }
162
Adam Cohen228da5a2011-07-27 22:23:47 -0700163 private static void deleteId(SQLiteDatabase db, long id) {
164 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
165 SqlArguments args = new SqlArguments(uri, null, null);
166 db.delete(args.table, args.where, args.args);
167 }
168
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800169 @Override
170 public Uri insert(Uri uri, ContentValues initialValues) {
171 SqlArguments args = new SqlArguments(uri);
172
Adam Cohena043fa82014-07-23 14:49:38 -0700173 // In very limited cases, we support system|signature permission apps to add to the db
174 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
175 if (externalAdd != null && "true".equals(externalAdd)) {
176 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
177 return null;
178 }
179 }
180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400182 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700183 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 if (rowId <= 0) return null;
185
186 uri = ContentUris.withAppendedId(uri, rowId);
187 sendNotify(uri);
188
189 return uri;
190 }
191
Adam Cohena043fa82014-07-23 14:49:38 -0700192
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193 @Override
194 public int bulkInsert(Uri uri, ContentValues[] values) {
195 SqlArguments args = new SqlArguments(uri);
196
197 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
198 db.beginTransaction();
199 try {
200 int numValues = values.length;
201 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400202 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700203 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
204 return 0;
205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 }
207 db.setTransactionSuccessful();
208 } finally {
209 db.endTransaction();
210 }
211
212 sendNotify(uri);
213 return values.length;
214 }
215
216 @Override
Yura085c8532014-02-11 15:15:29 +0000217 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
218 throws OperationApplicationException {
219 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
220 db.beginTransaction();
221 try {
222 ContentProviderResult[] result = super.applyBatch(operations);
223 db.setTransactionSuccessful();
224 return result;
225 } finally {
226 db.endTransaction();
227 }
228 }
229
230 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 public int delete(Uri uri, String selection, String[] selectionArgs) {
232 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
233
234 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
235 int count = db.delete(args.table, args.where, args.args);
236 if (count > 0) sendNotify(uri);
237
238 return count;
239 }
240
241 @Override
242 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
243 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
244
Chris Wren1ada10d2013-09-13 18:01:38 -0400245 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
247 int count = db.update(args.table, values, args.where, args.args);
248 if (count > 0) sendNotify(uri);
249
250 return count;
251 }
252
253 private void sendNotify(Uri uri) {
254 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
255 if (notify == null || "true".equals(notify)) {
256 getContext().getContentResolver().notifyChange(uri, null);
257 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400258
259 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400260 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700261 if (mListener != null) {
262 mListener.onLauncherProviderChange();
263 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400264 }
265
266 private void addModifiedTime(ContentValues values) {
267 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800268 }
269
Adam Cohendcd297f2013-06-18 13:13:40 -0700270 public long generateNewItemId() {
271 return mOpenHelper.generateNewItemId();
272 }
273
Winson Chungc763c4e2013-07-19 13:49:06 -0700274 public void updateMaxItemId(long id) {
275 mOpenHelper.updateMaxItemId(id);
276 }
277
Adam Cohendcd297f2013-06-18 13:13:40 -0700278 public long generateNewScreenId() {
279 return mOpenHelper.generateNewScreenId();
280 }
281
282 // This is only required one time while loading the workspace during the
283 // upgrade path, and should never be called from anywhere else.
284 public void updateMaxScreenId(long maxScreenId) {
285 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700286 }
287
Brian Muramatsu5524b492012-10-02 16:55:54 -0700288 /**
Adam Cohene25af792013-06-06 23:08:25 -0700289 * @param Should we load the old db for upgrade? first run only.
290 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700291 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400292 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700293 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
294
Winson Chungc763c4e2013-07-19 13:49:06 -0700295 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700296
Winson Chungc763c4e2013-07-19 13:49:06 -0700297 sJustLoadedFromOldDb = false;
298 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700299
300 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700301 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700302 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700303 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700304 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700305 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700306 }
307
308 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700309 * Clears all the data for a fresh start.
310 */
311 synchronized public void createEmptyDB() {
312 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
313 }
314
315 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700316 * Loads the default workspace based on the following priority scheme:
317 * 1) From a package provided by play store
318 * 2) From a partner configuration APK, already in the system image
319 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700320 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700321 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400322 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700323 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700324
Winson Chungc763c4e2013-07-19 13:49:06 -0700325 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500326 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200327
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700328 WorkspaceLoader loader = AutoInstallsLayout.get(getContext(),
329 mOpenHelper.mAppWidgetHost, mOpenHelper);
330
331 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700332 final Partner partner = Partner.get(getContext().getPackageManager());
333 if (partner != null && partner.hasDefaultLayout()) {
334 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700335 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700336 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700337 if (workspaceResId != 0) {
338 loader = new SimpleWorkspaceLoader(mOpenHelper, partnerRes, workspaceResId);
339 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700340 }
341 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700342
343 if (loader == null) {
344 loader = new SimpleWorkspaceLoader(mOpenHelper, getContext().getResources(),
345 getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700346 }
347
Michael Jurkab85f8a42012-04-25 15:48:32 -0700348 // Populate favorites table with initial favorites
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700349 SharedPreferences.Editor editor = sp.edit().remove(EMPTY_DATABASE_CREATED);
350 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700351 editor.commit();
352 }
353 }
354
Dan Sandlerd5024042014-01-09 15:01:33 -0500355 public void migrateLauncher2Shortcuts() {
356 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400357 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500358 }
359
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800360 private static int getDefaultWorkspaceResourceId() {
Winson Chungbe876472014-05-14 14:15:20 -0700361 LauncherAppState app = LauncherAppState.getInstance();
362 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Adam Cohencee8c662014-10-16 09:49:52 -0700363 return grid.defaultLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800364 }
365
Winson Chungc763c4e2013-07-19 13:49:06 -0700366 private static interface ContentValuesCallback {
367 public void onRow(ContentValues values);
368 }
369
Adam Cohen6dbe0492013-12-02 17:00:14 -0800370 private static boolean shouldImportLauncher2Database(Context context) {
371 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
372
373 // We don't import the old databse for tablets, as the grid size has changed.
374 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
375 }
376
Dan Sandlerd5024042014-01-09 15:01:33 -0500377 public void deleteDatabase() {
378 // Are you sure? (y/n)
379 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500380 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500381 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500382 if (dbFile.exists()) {
383 SQLiteDatabase.deleteDatabase(dbFile);
384 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500385 mOpenHelper = new DatabaseHelper(getContext());
386 }
387
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700388 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Jason Monk41314972014-03-03 16:11:30 -0500389 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800390 private static final String TAG_FAVORITES = "favorites";
391 private static final String TAG_FAVORITE = "favorite";
Mike Cleronb87bd162009-10-30 16:36:56 -0700392 private static final String TAG_APPWIDGET = "appwidget";
393 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700394 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700395 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700396 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400397 private static final String TAG_INCLUDE = "include";
Adam Cohencee8c662014-10-16 09:49:52 -0700398 private static final String TAG_FOLDER_ITEMS = "folderitems";
Winson Chung3d503fb2011-07-13 17:25:49 -0700399
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700400 // Style attrs -- "Favorite"
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700401 private static final String ATTR_CLASS_NAME = "className";
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700402 private static final String ATTR_PACKAGE_NAME = "packageName";
403 private static final String ATTR_CONTAINER = "container";
404 private static final String ATTR_SCREEN = "screen";
405 private static final String ATTR_X = "x";
406 private static final String ATTR_Y = "y";
407 private static final String ATTR_SPAN_X = "spanX";
408 private static final String ATTR_SPAN_Y = "spanY";
409 private static final String ATTR_ICON = "icon";
410 private static final String ATTR_TITLE = "title";
411 private static final String ATTR_URI = "uri";
412
413 // Style attrs -- "Include"
414 private static final String ATTR_WORKSPACE = "workspace";
Adam Cohencee8c662014-10-16 09:49:52 -0700415 private static final String ATTR_FOLDER_ITEMS = "folderItems";
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700416
417 // Style attrs -- "Extra"
418 private static final String ATTR_KEY = "key";
419 private static final String ATTR_VALUE = "value";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700420
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800421 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700422 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700423 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700424 private long mMaxItemId = -1;
425 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800426
Winson Chung0b560dd2014-01-21 13:00:26 -0800427 private boolean mNewDbCreated = false;
428
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800429 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100430 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800431 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700432 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700433 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700434
435 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
436 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700437 if (mMaxItemId == -1) {
438 mMaxItemId = initializeMaxItemId(getWritableDatabase());
439 }
440 if (mMaxScreenId == -1) {
441 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700442 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800443 }
444
Winson Chung0b560dd2014-01-21 13:00:26 -0800445 public boolean wasNewDbCreated() {
446 return mNewDbCreated;
447 }
448
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700449 /**
450 * Send notification that we've deleted the {@link AppWidgetHost},
451 * probably as part of the initial database creation. The receiver may
452 * want to re-call {@link AppWidgetHost#startListening()} to ensure
453 * callbacks are correctly set.
454 */
455 private void sendAppWidgetResetNotify() {
456 final ContentResolver resolver = mContext.getContentResolver();
457 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
458 }
459
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800460 @Override
461 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800462 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700463
Adam Cohendcd297f2013-06-18 13:13:40 -0700464 mMaxItemId = 1;
465 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800466 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700467
Kenny Guyed131872014-04-30 03:02:21 +0100468 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
469 long userSerialNumber = userManager.getSerialNumberForUser(
470 UserHandleCompat.myUserHandle());
471
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 db.execSQL("CREATE TABLE favorites (" +
473 "_id INTEGER PRIMARY KEY," +
474 "title TEXT," +
475 "intent TEXT," +
476 "container INTEGER," +
477 "screen INTEGER," +
478 "cellX INTEGER," +
479 "cellY INTEGER," +
480 "spanX INTEGER," +
481 "spanY INTEGER," +
482 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700483 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 "isShortcut INTEGER," +
485 "iconType INTEGER," +
486 "iconPackage TEXT," +
487 "iconResource TEXT," +
488 "icon BLOB," +
489 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400490 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400491 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500492 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100493 "restored INTEGER NOT NULL DEFAULT 0," +
494 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800495 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700496 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800497
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700498 // Database was just created, so wipe any previous widgets
499 if (mAppWidgetHost != null) {
500 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700501 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800502 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700503
Adam Cohen6dbe0492013-12-02 17:00:14 -0800504 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500505 // Try converting the old database
506 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
507 public void onRow(ContentValues values) {
508 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
509 if (container == Favorites.CONTAINER_DESKTOP) {
510 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
511 screen = (int) upgradeLauncherDb_permuteScreens(screen);
512 values.put(LauncherSettings.Favorites.SCREEN, screen);
513 }
514 }
515 };
516 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
517 "/old_favorites?notify=true");
518 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
519 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400520 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500521 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
522 // If we fail, then set a flag to load the default workspace
523 setFlagEmptyDbCreated();
524 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700525 }
526 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500527 // Right now, in non-default workspace cases, we want to run the final
528 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
529 // set that flag too.
530 setFlagJustLoadedOldDb();
531 } else {
532 // Fresh and clean launcher DB.
533 mMaxItemId = initializeMaxItemId(db);
534 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800535 }
536 }
537
Adam Cohendcd297f2013-06-18 13:13:40 -0700538 private void addWorkspacesTable(SQLiteDatabase db) {
539 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
540 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400541 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
542 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700543 ");");
544 }
545
Adam Cohen119285e2014-04-02 16:59:08 -0700546 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700547 // Delete items directly on the workspace who's screen id doesn't exist
548 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
549 // AND container = -100"
550 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
551 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700552 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700553 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
554 " AND " +
555 LauncherSettings.Favorites.CONTAINER + " = " +
556 LauncherSettings.Favorites.CONTAINER_DESKTOP;
557 db.execSQL(removeOrphanedDesktopItems);
558
559 // Delete items contained in folders which no longer exist (after above statement)
560 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
561 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
562 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
563 " WHERE " +
564 LauncherSettings.Favorites.CONTAINER + " <> " +
565 LauncherSettings.Favorites.CONTAINER_DESKTOP +
566 " AND "
567 + LauncherSettings.Favorites.CONTAINER + " <> " +
568 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
569 " AND "
570 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
571 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
572 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
573 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
574 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700575 }
576
Winson Chungc763c4e2013-07-19 13:49:06 -0700577 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400578 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700579 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
580 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700581 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
582 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700583 editor.commit();
584 }
585
Winson Chungc763c4e2013-07-19 13:49:06 -0700586 private void setFlagEmptyDbCreated() {
587 String spKey = LauncherAppState.getSharedPreferencesKey();
588 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
589 SharedPreferences.Editor editor = sp.edit();
590 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
591 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
592 editor.commit();
593 }
594
595 // We rearrange the screens from the old launcher
596 // 12345 -> 34512
597 private long upgradeLauncherDb_permuteScreens(long screen) {
598 if (screen >= 2) {
599 return screen - 2;
600 } else {
601 return screen + 3;
602 }
603 }
604
605 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
606 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800607 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800608 boolean converted = false;
609
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610 final ContentResolver resolver = mContext.getContentResolver();
611 Cursor cursor = null;
612
613 try {
614 cursor = resolver.query(uri, null, null, null, null);
615 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700616 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800617 }
618
619 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700620 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700622 if (cursor.getCount() > 0) {
623 converted = copyFromCursor(db, cursor, cb) > 0;
624 if (converted && deleteRows) {
625 resolver.delete(uri, null, null);
626 }
627 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 } finally {
629 cursor.close();
630 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700632
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700634 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800635 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700637
638 // Update max item id
639 mMaxItemId = initializeMaxItemId(db);
640 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641 }
642
643 return converted;
644 }
645
Winson Chungc763c4e2013-07-19 13:49:06 -0700646 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700647 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
649 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
650 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
651 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
652 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
653 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
654 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
655 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
656 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
657 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
658 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
659 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
660 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
661
662 ContentValues[] rows = new ContentValues[c.getCount()];
663 int i = 0;
664 while (c.moveToNext()) {
665 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700666 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
668 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
669 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
670 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
671 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
672 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
673 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
674 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700675 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800676 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
677 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
678 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
679 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
680 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700681 if (cb != null) {
682 cb.onRow(values);
683 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 rows[i++] = values;
685 }
686
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700688 if (i > 0) {
689 db.beginTransaction();
690 try {
691 int numValues = rows.length;
692 for (i = 0; i < numValues; i++) {
693 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
694 return 0;
695 } else {
696 total++;
697 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800698 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700699 db.setTransactionSuccessful();
700 } finally {
701 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800702 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800703 }
704
705 return total;
706 }
707
708 @Override
709 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700710 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700711
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800712 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700713 if (version < 3) {
714 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800715 db.beginTransaction();
716 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700717 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700719 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800720 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700721 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800722 } catch (SQLException ex) {
723 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800724 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800725 } finally {
726 db.endTransaction();
727 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700728
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800729 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700730 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800731 convertWidgets(db);
732 }
733 }
Romain Guy73b979d2009-06-09 12:57:21 -0700734
735 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800736 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700737 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700738
Romain Guy509cd6a2010-03-23 15:10:56 -0700739 // Where's version 5?
740 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400741 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700742 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
743 // but version 5 on there was the updateContactsShortcuts change
744 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
745 // The updateContactsShortcuts change is idempotent, so running it twice
746 // is okay so we'll do that when upgrading the devices that shipped with it.
747 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800748 // We went from 3 to 5 screens. Move everything 1 to the right
749 db.beginTransaction();
750 try {
751 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
752 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800753 } catch (SQLException ex) {
754 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800755 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800756 } finally {
757 db.endTransaction();
758 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700759
Romain Guy509cd6a2010-03-23 15:10:56 -0700760 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800761 if (updateContactsShortcuts(db)) {
762 version = 6;
763 }
764 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000765
766 if (version < 7) {
767 // Version 7 gets rid of the special search widget.
768 convertWidgets(db);
769 version = 7;
770 }
771
Joe Onorato0589f0f2010-02-08 13:44:00 -0800772 if (version < 8) {
773 // Version 8 (froyo) has the icons all normalized. This should
774 // already be the case in practice, but we now rely on it and don't
775 // resample the images each time.
776 normalizeIcons(db);
777 version = 8;
778 }
779
Winson Chung3d503fb2011-07-13 17:25:49 -0700780 if (version < 9) {
781 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
782 // before it gets a change to get set, so we need to read it here when we use it)
Adam Cohendcd297f2013-06-18 13:13:40 -0700783 if (mMaxItemId == -1) {
784 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700785 }
786
787 // Add default hotseat icons
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700788 loadFavorites(db, new SimpleWorkspaceLoader(this, mContext.getResources(),
789 R.xml.update_workspace));
Winson Chung3d503fb2011-07-13 17:25:49 -0700790 version = 9;
791 }
792
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700793 // We bumped the version three time during JB, once to update the launch flags, once to
794 // update the override for the default launch animation and once to set the mimetype
795 // to improve startup performance
796 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700797 // Contact shortcuts need a different set of flags to be launched now
798 // The updateContactsShortcuts change is idempotent, so we can keep using it like
799 // back in the Donut days
800 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700801 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700802 }
803
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 if (version < 13) {
805 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
806 // to persist workspace screens and their relative order.
807 mMaxScreenId = 0;
808
809 // This will never happen in the wild, but when we switch to using workspace
810 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700811 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700812
813 addWorkspacesTable(db);
814 version = 13;
815 }
816
Chris Wrend5e66bf2013-09-16 14:02:29 -0400817 if (version < 14) {
818 db.beginTransaction();
819 try {
820 // Insert new column for holding widget provider name
821 db.execSQL("ALTER TABLE favorites " +
822 "ADD COLUMN appWidgetProvider TEXT;");
823 db.setTransactionSuccessful();
824 version = 14;
825 } catch (SQLException ex) {
826 // Old version remains, which means we wipe old data
827 Log.e(TAG, ex.getMessage(), ex);
828 } finally {
829 db.endTransaction();
830 }
831 }
832
Chris Wren1ada10d2013-09-13 18:01:38 -0400833 if (version < 15) {
834 db.beginTransaction();
835 try {
836 // Insert new column for holding update timestamp
837 db.execSQL("ALTER TABLE favorites " +
838 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
839 db.execSQL("ALTER TABLE workspaceScreens " +
840 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
841 db.setTransactionSuccessful();
842 version = 15;
843 } catch (SQLException ex) {
844 // Old version remains, which means we wipe old data
845 Log.e(TAG, ex.getMessage(), ex);
846 } finally {
847 db.endTransaction();
848 }
849 }
850
Chris Wrenf4d08112014-01-16 18:13:56 -0500851
852 if (version < 16) {
853 db.beginTransaction();
854 try {
855 // Insert new column for holding restore status
856 db.execSQL("ALTER TABLE favorites " +
857 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
858 db.setTransactionSuccessful();
859 version = 16;
860 } catch (SQLException ex) {
861 // Old version remains, which means we wipe old data
862 Log.e(TAG, ex.getMessage(), ex);
863 } finally {
864 db.endTransaction();
865 }
866 }
867
Adam Cohen71e03b92014-02-21 14:09:53 -0800868 if (version < 17) {
869 // We use the db version upgrade here to identify users who may not have seen
870 // clings yet (because they weren't available), but for whom the clings are now
871 // available (tablet users). Because one of the possible cling flows (migration)
872 // is very destructive (wipes out workspaces), we want to prevent this from showing
873 // until clear data. We do so by marking that the clings have been shown.
874 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
875 version = 17;
876 }
877
Adam Cohen119285e2014-04-02 16:59:08 -0700878 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700879 // No-op
880 version = 18;
881 }
882
883 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700884 // Due to a data loss bug, some users may have items associated with screen ids
885 // which no longer exist. Since this can cause other problems, and since the user
886 // will never see these items anyway, we use database upgrade as an opportunity to
887 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700888 removeOrphanedItems(db);
889 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700890 }
891
Kenny Guyed131872014-04-30 03:02:21 +0100892 if (version < 20) {
893 // Add userId column
894 if (addProfileColumn(db)) {
895 version = 20;
896 }
897 // else old version remains, which means we wipe old data
898 }
899
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800901 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800902 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700903 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
904
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800905 onCreate(db);
906 }
907 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800908
Adam Cohen9b1d0622014-05-21 19:01:57 -0700909 @Override
910 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
911 // This shouldn't happen -- throw our hands up in the air and start over.
912 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
913 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700914 createEmptyDB(db);
915 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700916
Sunny Goyal42de82f2014-09-26 22:09:29 -0700917
918 /**
919 * Clears all the data for a fresh start.
920 */
921 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700922 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
923 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
924 onCreate(db);
925 }
926
Kenny Guyed131872014-04-30 03:02:21 +0100927 private boolean addProfileColumn(SQLiteDatabase db) {
928 db.beginTransaction();
929 try {
930 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
931 // Default to the serial number of this user, for older
932 // shortcuts.
933 long userSerialNumber = userManager.getSerialNumberForUser(
934 UserHandleCompat.myUserHandle());
935 // Insert new column for holding user serial number
936 db.execSQL("ALTER TABLE favorites " +
937 "ADD COLUMN profileId INTEGER DEFAULT "
938 + userSerialNumber + ";");
939 db.setTransactionSuccessful();
940 } catch (SQLException ex) {
941 // Old version remains, which means we wipe old data
942 Log.e(TAG, ex.getMessage(), ex);
943 return false;
944 } finally {
945 db.endTransaction();
946 }
947 return true;
948 }
949
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800950 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800951 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
952 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
953
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700954 Cursor c = null;
955 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800956 db.beginTransaction();
957 try {
958 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700959 c = db.query(TABLE_FAVORITES,
960 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800961 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700962 if (c == null) return false;
963
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800964 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700965
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800966 final int idIndex = c.getColumnIndex(Favorites._ID);
967 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700968
969 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800970 long favoriteId = c.getLong(idIndex);
971 final String intentUri = c.getString(intentIndex);
972 if (intentUri != null) {
973 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700974 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800975 android.util.Log.d("Home", intent.toString());
976 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700977 if (uri != null) {
978 final String data = uri.toString();
979 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
980 actionQuickContact.equals(intent.getAction())) &&
981 (data.startsWith("content://contacts/people/") ||
982 data.startsWith("content://com.android.contacts/" +
983 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800984
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700985 final Intent newIntent = new Intent(actionQuickContact);
986 // When starting from the launcher, start in a new, cleared task
987 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
988 // clear the whole thing preemptively here since
989 // QuickContactActivity will finish itself when launching other
990 // detail activities.
991 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
992 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700993 newIntent.putExtra(
994 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700995 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700996 // Determine the type and also put that in the shortcut
997 // (that can speed up launch a bit)
998 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800999
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001000 final ContentValues values = new ContentValues();
1001 values.put(LauncherSettings.Favorites.INTENT,
1002 newIntent.toUri(0));
1003
1004 String updateWhere = Favorites._ID + "=" + favoriteId;
1005 db.update(TABLE_FAVORITES, values, updateWhere, null);
1006 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001007 }
1008 } catch (RuntimeException ex) {
1009 Log.e(TAG, "Problem upgrading shortcut", ex);
1010 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001011 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001012 }
1013 }
1014 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001015
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001016 db.setTransactionSuccessful();
1017 } catch (SQLException ex) {
1018 Log.w(TAG, "Problem while upgrading contacts", ex);
1019 return false;
1020 } finally {
1021 db.endTransaction();
1022 if (c != null) {
1023 c.close();
1024 }
1025 }
1026
1027 return true;
1028 }
1029
Joe Onorato0589f0f2010-02-08 13:44:00 -08001030 private void normalizeIcons(SQLiteDatabase db) {
1031 Log.d(TAG, "normalizing icons");
1032
Joe Onorato346e1292010-02-18 10:34:24 -05001033 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001034 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -04001035 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001036 try {
1037 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -04001038 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -06001039 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -08001040
1041 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
1042 Favorites.ICON_TYPE_BITMAP, null);
1043
1044 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1045 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
1046
1047 while (c.moveToNext()) {
1048 long id = c.getLong(idIndex);
1049 byte[] data = c.getBlob(iconIndex);
1050 try {
Sunny Goyal2fce90c2014-10-07 12:01:58 -07001051 Bitmap bitmap = Utilities.createIconBitmap(
Joe Onorato0589f0f2010-02-08 13:44:00 -08001052 BitmapFactory.decodeByteArray(data, 0, data.length),
1053 mContext);
1054 if (bitmap != null) {
1055 update.bindLong(1, id);
1056 data = ItemInfo.flattenBitmap(bitmap);
1057 if (data != null) {
1058 update.bindBlob(2, data);
1059 update.execute();
1060 }
1061 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001062 }
1063 } catch (Exception e) {
1064 if (!logged) {
1065 Log.e(TAG, "Failed normalizing icon " + id, e);
1066 } else {
1067 Log.e(TAG, "Also failed normalizing icon " + id);
1068 }
1069 logged = true;
1070 }
1071 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001072 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001073 } catch (SQLException ex) {
1074 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1075 } finally {
1076 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001077 if (update != null) {
1078 update.close();
1079 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001080 if (c != null) {
1081 c.close();
1082 }
1083 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001084 }
1085
1086 // Generates a new ID to use for an object in your database. This method should be only
1087 // called from the main UI thread. As an exception, we do call it when we call the
1088 // constructor from the worker thread; however, this doesn't extend until after the
1089 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1090 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001091 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001092 public long generateNewItemId() {
1093 if (mMaxItemId < 0) {
1094 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001095 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001096 mMaxItemId += 1;
1097 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001098 }
1099
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001100 @Override
1101 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
1102 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
1103 }
1104
Winson Chungc763c4e2013-07-19 13:49:06 -07001105 public void updateMaxItemId(long id) {
1106 mMaxItemId = id + 1;
1107 }
1108
Chris Wren5dee7af2013-12-20 17:22:11 -05001109 public void checkId(String table, ContentValues values) {
1110 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1111 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1112 mMaxScreenId = Math.max(id, mMaxScreenId);
1113 } else {
1114 mMaxItemId = Math.max(id, mMaxItemId);
1115 }
1116 }
1117
Adam Cohendcd297f2013-06-18 13:13:40 -07001118 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001119 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1120
1121 // get the result
1122 final int maxIdIndex = 0;
1123 long id = -1;
1124 if (c != null && c.moveToNext()) {
1125 id = c.getLong(maxIdIndex);
1126 }
Michael Jurka5130e402011-10-13 04:55:35 -07001127 if (c != null) {
1128 c.close();
1129 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001130
1131 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001132 throw new RuntimeException("Error: could not query max item id");
1133 }
1134
1135 return id;
1136 }
1137
1138 // Generates a new ID to use for an workspace screen in your database. This method
1139 // should be only called from the main UI thread. As an exception, we do call it when we
1140 // call the constructor from the worker thread; however, this doesn't extend until after the
1141 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1142 // after that point
1143 public long generateNewScreenId() {
1144 if (mMaxScreenId < 0) {
1145 throw new RuntimeException("Error: max screen id was not initialized");
1146 }
1147 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001148 // Log to disk
1149 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 return mMaxScreenId;
1151 }
1152
1153 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001154 // Log to disk
1155 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001156 mMaxScreenId = maxScreenId;
1157 }
1158
1159 private long initializeMaxScreenId(SQLiteDatabase db) {
1160 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1161
1162 // get the result
1163 final int maxIdIndex = 0;
1164 long id = -1;
1165 if (c != null && c.moveToNext()) {
1166 id = c.getLong(maxIdIndex);
1167 }
1168 if (c != null) {
1169 c.close();
1170 }
1171
1172 if (id == -1) {
1173 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001174 }
1175
Winson Chunga90303b2013-11-15 13:05:06 -08001176 // Log to disk
1177 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001178 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001179 }
1180
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001182 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001183 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001184 */
1185 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001186 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001187 final int[] bindSources = new int[] {
1188 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1189 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001190 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001191 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001192
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001194
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001195 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001196
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001197 db.beginTransaction();
1198 try {
1199 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001200 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001201 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001202
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001203 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001204
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001205 final ContentValues values = new ContentValues();
1206 while (c != null && c.moveToNext()) {
1207 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001208 int favoriteType = c.getInt(1);
1209
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001210 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001211 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001212 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001213
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001214 if (LOGD) {
1215 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1216 + " for favoriteId=" + favoriteId);
1217 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001218 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001219 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1220 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1221
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001222 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001223 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1224 values.put(LauncherSettings.Favorites.SPANX, 4);
1225 values.put(LauncherSettings.Favorites.SPANY, 1);
1226 } else {
1227 values.put(LauncherSettings.Favorites.SPANX, 2);
1228 values.put(LauncherSettings.Favorites.SPANY, 2);
1229 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001230
1231 String updateWhere = Favorites._ID + "=" + favoriteId;
1232 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001233
Bjorn Bringert34251342009-12-15 13:33:11 +00001234 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001235 // TODO: check return value
1236 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001237 new ComponentName("com.android.alarmclock",
1238 "com.android.alarmclock.AnalogAppWidgetProvider"));
1239 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001240 // TODO: check return value
1241 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001242 new ComponentName("com.android.camera",
1243 "com.android.camera.PhotoAppWidgetProvider"));
1244 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001245 // TODO: check return value
1246 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001247 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001248 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001249 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001250 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001251 }
1252 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001253
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001254 db.setTransactionSuccessful();
1255 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001256 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001257 } finally {
1258 db.endTransaction();
1259 if (c != null) {
1260 c.close();
1261 }
1262 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001263
1264 // Update max item id
1265 mMaxItemId = initializeMaxItemId(db);
1266 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001267 }
1268
Adam Cohena043fa82014-07-23 14:49:38 -07001269 private boolean initializeExternalAdd(ContentValues values) {
1270 // 1. Ensure that externally added items have a valid item id
1271 long id = generateNewItemId();
1272 values.put(LauncherSettings.Favorites._ID, id);
1273
1274 // 2. In the case of an app widget, and if no app widget id is specified, we
1275 // attempt allocate and bind the widget.
1276 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1277 if (itemType != null &&
1278 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1279 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1280
1281 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1282 ComponentName cn = ComponentName.unflattenFromString(
1283 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1284
1285 if (cn != null) {
1286 try {
1287 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001288 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001289 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001290 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001291 }
1292 } catch (RuntimeException e) {
1293 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001294 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001295 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001296 } else {
1297 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001298 }
1299 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001300
1301 // Add screen id if not present
1302 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1303 if (!addScreenIdIfNecessary(screenId)) {
1304 return false;
1305 }
Adam Cohena043fa82014-07-23 14:49:38 -07001306 return true;
1307 }
1308
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001309 // Returns true of screen id exists, or if successfully added
1310 private boolean addScreenIdIfNecessary(long screenId) {
1311 if (!hasScreenId(screenId)) {
1312 int rank = getMaxScreenRank() + 1;
1313
1314 ContentValues v = new ContentValues();
1315 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1316 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1317 if (dbInsertAndCheck(this, getWritableDatabase(),
1318 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1319 return false;
1320 }
1321 }
1322 return true;
1323 }
1324
1325 private boolean hasScreenId(long screenId) {
1326 SQLiteDatabase db = getWritableDatabase();
1327 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1328 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1329 if (c != null) {
1330 int count = c.getCount();
1331 c.close();
1332 return count > 0;
1333 } else {
1334 return false;
1335 }
1336 }
1337
1338 private int getMaxScreenRank() {
1339 SQLiteDatabase db = getWritableDatabase();
1340 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1341 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1342
1343 // get the result
1344 final int maxRankIndex = 0;
1345 int rank = -1;
1346 if (c != null && c.moveToNext()) {
1347 rank = c.getInt(maxRankIndex);
1348 }
1349 if (c != null) {
1350 c.close();
1351 }
1352
1353 return rank;
1354 }
1355
Michael Jurka8b805b12012-04-18 14:23:14 -07001356 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1357 throws XmlPullParserException, IOException {
1358 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001359 while ((type = parser.next()) != XmlPullParser.START_TAG
1360 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001361 ;
1362 }
1363
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001364 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001365 throw new XmlPullParserException("No start tag found");
1366 }
1367
1368 if (!parser.getName().equals(firstElementName)) {
1369 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1370 ", expected " + firstElementName);
1371 }
1372 }
1373
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001374 private static Intent buildMainIntent() {
1375 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1376 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1377 return intent;
1378 }
1379
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001380 private int loadFavorites(SQLiteDatabase db, WorkspaceLoader loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001381 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001382 // TODO: Use multiple loaders with fall-back and transaction.
1383 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001384
1385 // Add the screens specified by the items above
1386 Collections.sort(screenIds);
1387 int rank = 0;
1388 ContentValues values = new ContentValues();
1389 for (Long id : screenIds) {
1390 values.clear();
1391 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1392 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1393 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1394 throw new RuntimeException("Failed initialize screen table"
1395 + "from default layout");
1396 }
1397 rank++;
1398 }
1399
1400 // Ensure that the max ids are initialized
1401 mMaxItemId = initializeMaxItemId(db);
1402 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001403
Adam Cohen71483f42014-05-15 14:04:01 -07001404 return count;
1405 }
1406
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001407 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001408 * Loads the default set of favorite packages from an xml file.
1409 *
1410 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001411 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001412 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001413 */
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001414 private int loadFavoritesRecursive(SQLiteDatabase db, Resources res, int workspaceResourceId,
Adam Cohen71483f42014-05-15 14:04:01 -07001415 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001416
Adam Cohen71483f42014-05-15 14:04:01 -07001417 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001418 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1419
Adam Cohen71483f42014-05-15 14:04:01 -07001420 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001421 try {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001422 XmlResourceParser parser = res.getXml(workspaceResourceId);
Michael Jurka8b805b12012-04-18 14:23:14 -07001423 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001424
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001425 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001426
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001427 int type;
1428 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1429 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1430
1431 if (type != XmlPullParser.START_TAG) {
1432 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001433 }
1434
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001435 boolean added = false;
1436 final String name = parser.getName();
1437
Daniel Sandler57dac262013-10-03 13:28:36 -04001438 if (TAG_INCLUDE.equals(name)) {
Daniel Sandler57dac262013-10-03 13:28:36 -04001439
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001440 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
Daniel Sandler57dac262013-10-03 13:28:36 -04001441
1442 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1443 "", resId));
1444
1445 if (resId != 0 && resId != workspaceResourceId) {
1446 // recursively load some more favorites, why not?
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001447 count += loadFavoritesRecursive(db, res, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001448 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001449 } else {
1450 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1451 }
1452
Daniel Sandler57dac262013-10-03 13:28:36 -04001453 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1454 continue;
1455 }
1456
1457 // Assuming it's a <favorite> at this point
Winson Chung3d503fb2011-07-13 17:25:49 -07001458 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001459 String strContainer = getAttributeValue(parser, ATTR_CONTAINER);
1460 if (strContainer != null) {
1461 container = Long.valueOf(strContainer);
Winson Chung3d503fb2011-07-13 17:25:49 -07001462 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001463
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001464 String screen = getAttributeValue(parser, ATTR_SCREEN);
1465 String x = getAttributeValue(parser, ATTR_X);
1466 String y = getAttributeValue(parser, ATTR_Y);
Winson Chung6d092682011-11-16 18:43:26 -08001467
Winson Chung6d092682011-11-16 18:43:26 -08001468 values.clear();
1469 values.put(LauncherSettings.Favorites.CONTAINER, container);
1470 values.put(LauncherSettings.Favorites.SCREEN, screen);
1471 values.put(LauncherSettings.Favorites.CELLX, x);
1472 values.put(LauncherSettings.Favorites.CELLY, y);
1473
Daniel Sandler57dac262013-10-03 13:28:36 -04001474 if (LOGD) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001475 final String title = getAttributeValue(parser, ATTR_TITLE);
1476 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
Daniel Sandler57dac262013-10-03 13:28:36 -04001477 final String something = title != null ? title : pkg;
1478 Log.v(TAG, String.format(
1479 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1480 "", name,
1481 (something == null ? "" : (" \"" + something + "\"")),
1482 container, screen, x, y));
1483 }
1484
Winson Chung6d092682011-11-16 18:43:26 -08001485 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001486 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001487 added = id >= 0;
Winson Chung6d092682011-11-16 18:43:26 -08001488 } else if (TAG_APPWIDGET.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001489 added = addAppWidget(parser, type, db, values);
Winson Chung6d092682011-11-16 18:43:26 -08001490 } else if (TAG_SHORTCUT.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001491 long id = addUriShortcut(db, values, res, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001492 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001493 } else if (TAG_RESOLVE.equals(name)) {
1494 // This looks through the contained favorites (or meta-favorites) and
1495 // attempts to add them as shortcuts in the fallback group's location
1496 // until one is added successfully.
1497 added = false;
1498 final int groupDepth = parser.getDepth();
1499 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1500 parser.getDepth() > groupDepth) {
1501 if (type != XmlPullParser.START_TAG) {
1502 continue;
1503 }
1504 final String fallback_item_name = parser.getName();
Jason Monk41314972014-03-03 16:11:30 -05001505 if (!added) {
1506 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001507 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001508 added = id >= 0;
1509 } else {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001510 Log.e(TAG, "Fallback groups can contain only favorites, found "
1511 + fallback_item_name);
Jason Monk41314972014-03-03 16:11:30 -05001512 }
1513 }
Jason Monk41314972014-03-03 16:11:30 -05001514 }
Winson Chung6d092682011-11-16 18:43:26 -08001515 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001516 // Folder contents are nested in this XML file
Adam Cohen43f3ca02014-07-25 13:24:09 -07001517 added = loadFolder(db, values, res, parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001518
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001519 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1520 // Folder contents come from an external XML resource
1521 final Partner partner = Partner.get(mPackageManager);
1522 if (partner != null) {
1523 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -07001524 final int resId = partnerRes.getIdentifier(Partner.RES_FOLDER,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001525 "xml", partner.getPackageName());
1526 if (resId != 0) {
1527 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1528 beginDocument(partnerParser, TAG_FOLDER);
1529 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001530 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001531 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001532 }
Adam Cohen71483f42014-05-15 14:04:01 -07001533 if (added) {
1534 long screenId = Long.parseLong(screen);
1535 // Keep track of the set of screens which need to be added to the db.
1536 if (!screenIds.contains(screenId) &&
1537 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1538 screenIds.add(screenId);
1539 }
1540 count++;
1541 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001542 }
1543 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001544 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001545 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001546 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001547 } catch (RuntimeException e) {
1548 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001549 }
Adam Cohen71483f42014-05-15 14:04:01 -07001550 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001551 }
1552
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001553 /**
Adam Coheneb1ac422014-10-14 08:55:28 -07001554 * Parse folder items starting at {@link XmlPullParser} location. Allow recursive
1555 * includes of items.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001556 */
Adam Coheneb1ac422014-10-14 08:55:28 -07001557 private void addToFolder(SQLiteDatabase db, Resources res, XmlResourceParser parser,
1558 ArrayList<Long> folderItems, long folderId) throws IOException, XmlPullParserException {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001559 int type;
1560 int folderDepth = parser.getDepth();
1561 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1562 parser.getDepth() > folderDepth) {
1563 if (type != XmlPullParser.START_TAG) {
1564 continue;
1565 }
1566 final String tag = parser.getName();
1567
1568 final ContentValues childValues = new ContentValues();
1569 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1570
1571 if (LOGD) {
1572 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1573 final String uri = getAttributeValue(parser, ATTR_URI);
1574 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1575 tag, uri != null ? uri : pkg));
1576 }
1577
1578 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1579 final long id = addAppShortcut(db, childValues, parser);
1580 if (id >= 0) {
1581 folderItems.add(id);
1582 }
1583 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1584 final long id = addUriShortcut(db, childValues, res, parser);
1585 if (id >= 0) {
1586 folderItems.add(id);
1587 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001588 } else if (TAG_INCLUDE.equals(tag) && folderId >= 0) {
Adam Cohencee8c662014-10-16 09:49:52 -07001589 final int resId = getAttributeResourceValue(parser, ATTR_FOLDER_ITEMS, 0);
1590 XmlResourceParser itemsParser = res.getXml(resId);
1591 beginDocument(itemsParser, TAG_FOLDER_ITEMS);
1592 addToFolder(db, res, itemsParser, folderItems, folderId);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001593 } else {
1594 throw new RuntimeException("Folders can contain only shortcuts");
1595 }
1596 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001597 }
1598
1599 /**
1600 * Parse folder starting at current {@link XmlPullParser} location.
1601 */
1602 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1603 XmlResourceParser parser) throws IOException, XmlPullParserException {
1604 final String title;
1605 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1606 if (titleResId != 0) {
1607 title = res.getString(titleResId);
1608 } else {
1609 title = mContext.getResources().getString(R.string.folder_name);
1610 }
1611
1612 values.put(LauncherSettings.Favorites.TITLE, title);
1613 long folderId = addFolder(db, values);
1614 boolean added = folderId >= 0;
1615
1616 ArrayList<Long> folderItems = new ArrayList<Long>();
1617 addToFolder(db, res, parser, folderItems, folderId);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001618
1619 // We can only have folders with >= 2 items, so we need to remove the
1620 // folder and clean up if less than 2 items were included, or some
1621 // failed to add, and less than 2 were actually added
1622 if (folderItems.size() < 2 && folderId >= 0) {
1623 // Delete the folder
1624 deleteId(db, folderId);
1625
1626 // If we have a single item, promote it to where the folder
1627 // would have been.
1628 if (folderItems.size() == 1) {
1629 final ContentValues childValues = new ContentValues();
1630 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1631 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1632 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1633 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1634
1635 final long id = folderItems.get(0);
1636 db.update(TABLE_FAVORITES, childValues,
1637 LauncherSettings.Favorites._ID + "=" + id, null);
1638 } else {
1639 added = false;
1640 }
1641 }
1642 return added;
1643 }
1644
Jason Monk41314972014-03-03 16:11:30 -05001645 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1646 // logical choice for what shortcut should be used for that intent exists, then it is
1647 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001648 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1649 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001650 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001651 try {
Jason Monk41314972014-03-03 16:11:30 -05001652 metaIntent = Intent.parseUri(intentUri, 0);
1653 } catch (URISyntaxException e) {
1654 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1655 return -1;
1656 }
1657
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001658 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001659 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001660 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001661 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1662
1663 // Verify that the result is an app and not just the resolver dialog asking which
1664 // app to use.
1665 if (wouldLaunchResolverActivity(resolved, appList)) {
1666 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001667 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001668 if (systemApp == null) {
1669 // There is no logical choice for this meta-favorite, so rather than making
1670 // a bad choice just add nothing.
1671 Log.w(TAG, "No preference or single system activity found for "
1672 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001673 return -1;
1674 }
Jason Monk41314972014-03-03 16:11:30 -05001675 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001676 }
Jason Monk41314972014-03-03 16:11:30 -05001677 final ActivityInfo info = resolved.activityInfo;
Jason Monkc3009c02014-08-20 09:41:21 -04001678 final Intent intent = mPackageManager.getLaunchIntentForPackage(info.packageName);
1679 if (intent == null) {
1680 return -1;
1681 }
Jason Monk41314972014-03-03 16:11:30 -05001682 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1683 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1684
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001685 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001686 }
1687
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001688 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001689 ResolveInfo systemResolve = null;
1690 final int N = appList.size();
1691 for (int i = 0; i < N; ++i) {
1692 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001693 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001694 appList.get(i).activityInfo.packageName, 0);
1695 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1696 if (systemResolve != null) {
1697 return null;
1698 } else {
1699 systemResolve = appList.get(i);
1700 }
1701 }
1702 } catch (PackageManager.NameNotFoundException e) {
1703 Log.w(TAG, "Unable to get info about resolve results", e);
1704 return null;
1705 }
1706 }
1707 return systemResolve;
1708 }
1709
1710 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1711 List<ResolveInfo> appList) {
1712 // If the list contains the above resolved activity, then it can't be
1713 // ResolverActivity itself.
1714 for (int i = 0; i < appList.size(); ++i) {
1715 ResolveInfo tmp = appList.get(i);
1716 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1717 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1718 return false;
1719 }
1720 }
1721 return true;
1722 }
1723
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001724 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1725 XmlResourceParser parser) {
1726 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1727 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1728 final String uri = getAttributeValue(parser, ATTR_URI);
1729
1730 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001731 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001732 try {
1733 ComponentName cn;
1734 try {
1735 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001736 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001737 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001738 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001739 new String[] { packageName });
1740 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001741 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001742 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001743 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001744 intent.setComponent(cn);
1745 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1746 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1747
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001748 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001749 intent);
1750 } catch (PackageManager.NameNotFoundException e) {
1751 Log.w(TAG, "Unable to add favorite: " + packageName +
1752 "/" + className, e);
1753 }
1754 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001755 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001756 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001757 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001758 } else {
1759 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1760 return -1;
1761 }
1762 }
1763
1764 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1765 Intent intent) {
1766 long id = generateNewItemId();
1767 values.put(Favorites.INTENT, intent.toUri(0));
1768 values.put(Favorites.TITLE, title);
1769 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1770 values.put(Favorites.SPANX, 1);
1771 values.put(Favorites.SPANY, 1);
1772 values.put(Favorites._ID, id);
1773 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1774 return -1;
1775 } else {
1776 return id;
1777 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001778 }
1779
1780 private long addFolder(SQLiteDatabase db, ContentValues values) {
1781 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1782 values.put(Favorites.SPANX, 1);
1783 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001784 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001785 values.put(Favorites._ID, id);
1786 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1787 return -1;
1788 } else {
1789 return id;
1790 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001791 }
1792
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001793 private ComponentName getSearchWidgetProvider() {
1794 SearchManager searchManager =
1795 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1796 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1797 if (searchComponent == null) return null;
1798 return getProviderInPackage(searchComponent.getPackageName());
1799 }
1800
1801 /**
1802 * Gets an appwidget provider from the given package. If the package contains more than
1803 * one appwidget provider, an arbitrary one is returned.
1804 */
1805 private ComponentName getProviderInPackage(String packageName) {
1806 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1807 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1808 if (providers == null) return null;
1809 final int providerCount = providers.size();
1810 for (int i = 0; i < providerCount; i++) {
1811 ComponentName provider = providers.get(i).provider;
1812 if (provider != null && provider.getPackageName().equals(packageName)) {
1813 return provider;
1814 }
1815 }
1816 return null;
1817 }
1818
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001819 private boolean addAppWidget(XmlResourceParser parser, int type,
1820 SQLiteDatabase db, ContentValues values)
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001821 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001822
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001823 String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1824 String className = getAttributeValue(parser, ATTR_CLASS_NAME);
Mike Cleronb87bd162009-10-30 16:36:56 -07001825
1826 if (packageName == null || className == null) {
1827 return false;
1828 }
Romain Guy693599f2010-03-23 10:58:18 -07001829
1830 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001831 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001832 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001833 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001834 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001835 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001836 new String[] { packageName });
1837 cn = new ComponentName(packages[0], className);
1838 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001839 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001840 } catch (Exception e1) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001841 System.out.println("Can't find widget provider: " + className);
Romain Guy693599f2010-03-23 10:58:18 -07001842 hasPackage = false;
1843 }
1844 }
1845
1846 if (hasPackage) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001847 String spanX = getAttributeValue(parser, ATTR_SPAN_X);
1848 String spanY = getAttributeValue(parser, ATTR_SPAN_Y);
1849
1850 values.put(Favorites.SPANX, spanX);
1851 values.put(Favorites.SPANY, spanY);
Winson Chungb3302ae2012-05-01 10:19:14 -07001852
1853 // Read the extras
1854 Bundle extras = new Bundle();
1855 int widgetDepth = parser.getDepth();
1856 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1857 parser.getDepth() > widgetDepth) {
1858 if (type != XmlPullParser.START_TAG) {
1859 continue;
1860 }
1861
Winson Chungb3302ae2012-05-01 10:19:14 -07001862 if (TAG_EXTRA.equals(parser.getName())) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001863 String key = getAttributeValue(parser, ATTR_KEY);
1864 String value = getAttributeValue(parser, ATTR_VALUE);
Winson Chungb3302ae2012-05-01 10:19:14 -07001865 if (key != null && value != null) {
1866 extras.putString(key, value);
1867 } else {
1868 throw new RuntimeException("Widget extras must have a key and value");
1869 }
1870 } else {
1871 throw new RuntimeException("Widgets can contain only extras");
1872 }
Winson Chungb3302ae2012-05-01 10:19:14 -07001873 }
1874
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001875 return addAppWidget(db, values, cn, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001876 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001877
Romain Guy693599f2010-03-23 10:58:18 -07001878 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001879 }
Adam Cohena043fa82014-07-23 14:49:38 -07001880
Bjorn Bringert7984c942009-12-09 15:38:25 +00001881 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001882 Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001883 boolean allocatedAppWidgets = false;
1884 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1885
1886 try {
1887 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001888
Mike Cleronb87bd162009-10-30 16:36:56 -07001889 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Mike Cleronb87bd162009-10-30 16:36:56 -07001890 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001891 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001892 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001893 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001894
1895 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001896
Michael Jurka8b805b12012-04-18 14:23:14 -07001897 // TODO: need to check return value
1898 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001899
1900 // Send a broadcast to configure the widget
1901 if (extras != null && !extras.isEmpty()) {
1902 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1903 intent.setComponent(cn);
1904 intent.putExtras(extras);
1905 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1906 mContext.sendBroadcast(intent);
1907 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001908 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001909 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001910 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001911
Mike Cleronb87bd162009-10-30 16:36:56 -07001912 return allocatedAppWidgets;
1913 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001914
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001915 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1916 XmlResourceParser parser) {
1917 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1918 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001919
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001920 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001921 String uri = null;
1922 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001923 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001924 intent = Intent.parseUri(uri, 0);
1925 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001926 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001927 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001928 }
1929
1930 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001931 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001932 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001933 }
1934
Adam Cohendcd297f2013-06-18 13:13:40 -07001935 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001936 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1937 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001938 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001939 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1940 values.put(Favorites.SPANX, 1);
1941 values.put(Favorites.SPANY, 1);
1942 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001943 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1944 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001945 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001946
Adam Cohen228da5a2011-07-27 22:23:47 -07001947 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1948 return -1;
1949 }
1950 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001951 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001952
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001953 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001954 final ContentResolver resolver = mContext.getContentResolver();
1955 Cursor c = null;
1956 int count = 0;
1957 int curScreen = 0;
1958
1959 try {
1960 c = resolver.query(uri, null, null, null, "title ASC");
1961 } catch (Exception e) {
1962 // Ignore
1963 }
1964
Dan Sandlerd5024042014-01-09 15:01:33 -05001965 // We already have a favorites database in the old provider
1966 if (c != null) {
1967 try {
1968 if (c.getCount() > 0) {
1969 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1970 final int intentIndex
1971 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1972 final int titleIndex
1973 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1974 final int iconTypeIndex
1975 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1976 final int iconIndex
1977 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1978 final int iconPackageIndex
1979 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1980 final int iconResourceIndex
1981 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1982 final int containerIndex
1983 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1984 final int itemTypeIndex
1985 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1986 final int screenIndex
1987 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1988 final int cellXIndex
1989 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1990 final int cellYIndex
1991 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1992 final int uriIndex
1993 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1994 final int displayModeIndex
1995 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001996 final int profileIndex
1997 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001998
1999 int i = 0;
2000 int curX = 0;
2001 int curY = 0;
2002
2003 final LauncherAppState app = LauncherAppState.getInstance();
2004 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
2005 final int width = (int) grid.numColumns;
2006 final int height = (int) grid.numRows;
2007 final int hotseatWidth = (int) grid.numHotseatIcons;
2008
2009 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
2010
Adam Cohen72960972014-01-15 18:13:55 -08002011 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
2012 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002013 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05002014
2015 while (c.moveToNext()) {
2016 final int itemType = c.getInt(itemTypeIndex);
2017 if (itemType != Favorites.ITEM_TYPE_APPLICATION
2018 && itemType != Favorites.ITEM_TYPE_SHORTCUT
2019 && itemType != Favorites.ITEM_TYPE_FOLDER) {
2020 continue;
2021 }
2022
2023 final int cellX = c.getInt(cellXIndex);
2024 final int cellY = c.getInt(cellYIndex);
2025 final int screen = c.getInt(screenIndex);
2026 int container = c.getInt(containerIndex);
2027 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01002028
2029 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
2030 UserHandleCompat userHandle;
2031 final long userSerialNumber;
2032 if (profileIndex != -1 && !c.isNull(profileIndex)) {
2033 userSerialNumber = c.getInt(profileIndex);
2034 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
2035 } else {
2036 // Default to the serial number of this user, for older
2037 // shortcuts.
2038 userHandle = UserHandleCompat.myUserHandle();
2039 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
2040 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002041 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002042 + c.getString(titleIndex) + "\" ("
2043 + cellX + "," + cellY + "@"
2044 + LauncherSettings.Favorites.containerToString(container)
2045 + "/" + screen
2046 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05002047
2048 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08002049
2050 final Intent intent;
2051 final ComponentName cn;
2052 try {
2053 intent = Intent.parseUri(intentStr, 0);
2054 } catch (URISyntaxException e) {
2055 // bogus intent?
2056 Launcher.addDumpLog(TAG,
2057 "skipping invalid intent uri", true);
2058 continue;
2059 }
2060
2061 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05002062 if (TextUtils.isEmpty(intentStr)) {
2063 // no intent? no icon
2064 Launcher.addDumpLog(TAG, "skipping empty intent", true);
2065 continue;
Adam Cohen72960972014-01-15 18:13:55 -08002066 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01002067 !LauncherModel.isValidPackageActivity(mContext, cn,
2068 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08002069 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08002070 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08002071 "no longer exists.", true);
2072 continue;
Adam Cohen72960972014-01-15 18:13:55 -08002073 } else if (container ==
2074 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2075 // Dedupe icons directly on the workspace
2076
Adam Cohen556f6132014-01-15 15:18:08 -08002077 // Canonicalize
2078 // the Play Store sets the package parameter, but Launcher
2079 // does not, so we clear that out to keep them the same
2080 intent.setPackage(null);
2081 final String key = intent.toUri(0);
2082 if (seenIntents.contains(key)) {
2083 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05002084 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08002085 } else {
2086 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05002087 }
2088 }
2089 }
2090
2091 ContentValues values = new ContentValues(c.getColumnCount());
2092 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
2093 values.put(LauncherSettings.Favorites.INTENT, intentStr);
2094 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
2095 values.put(LauncherSettings.Favorites.ICON_TYPE,
2096 c.getInt(iconTypeIndex));
2097 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
2098 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
2099 c.getString(iconPackageIndex));
2100 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
2101 c.getString(iconResourceIndex));
2102 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
2103 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
2104 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
2105 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
2106 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01002107 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05002108
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002109 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2110 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05002111 }
2112
2113 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2114 // In a folder or in the hotseat, preserve position
2115 values.put(LauncherSettings.Favorites.SCREEN, screen);
2116 values.put(LauncherSettings.Favorites.CELLX, cellX);
2117 values.put(LauncherSettings.Favorites.CELLY, cellY);
2118 } else {
Adam Cohen72960972014-01-15 18:13:55 -08002119 // For items contained directly on one of the workspace screen,
2120 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05002121 }
2122
2123 values.put(LauncherSettings.Favorites.CONTAINER, container);
2124
Adam Cohen72960972014-01-15 18:13:55 -08002125 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
2126 shortcuts.add(values);
2127 } else {
2128 folders.add(values);
2129 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002130 }
2131
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002132 // Now that we have all the hotseat icons, let's go through them left-right
2133 // and assign valid locations for them in the new hotseat
2134 final int N = hotseat.size();
2135 for (int idx=0; idx<N; idx++) {
2136 int hotseatX = hotseat.keyAt(idx);
2137 ContentValues values = hotseat.valueAt(idx);
2138
2139 if (hotseatX == grid.hotseatAllAppsRank) {
2140 // let's drop this in the next available hole in the hotseat
2141 while (++hotseatX < hotseatWidth) {
2142 if (hotseat.get(hotseatX) == null) {
2143 // found a spot! move it here
2144 values.put(LauncherSettings.Favorites.SCREEN,
2145 hotseatX);
2146 break;
2147 }
2148 }
2149 }
2150 if (hotseatX >= hotseatWidth) {
2151 // no room for you in the hotseat? it's off to the desktop with you
2152 values.put(LauncherSettings.Favorites.CONTAINER,
2153 Favorites.CONTAINER_DESKTOP);
2154 }
2155 }
2156
Adam Cohen72960972014-01-15 18:13:55 -08002157 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2158 // Folders first
2159 allItems.addAll(folders);
2160 // Then shortcuts
2161 allItems.addAll(shortcuts);
2162
2163 // Layout all the folders
2164 for (ContentValues values: allItems) {
2165 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2166 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2167 // Hotseat items and folder items have already had their
2168 // location information set. Nothing to be done here.
2169 continue;
2170 }
2171 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2172 values.put(LauncherSettings.Favorites.CELLX, curX);
2173 values.put(LauncherSettings.Favorites.CELLY, curY);
2174 curX = (curX + 1) % width;
2175 if (curX == 0) {
2176 curY = (curY + 1);
2177 }
2178 // Leave the last row of icons blank on every screen
2179 if (curY == height - 1) {
2180 curScreen = (int) generateNewScreenId();
2181 curY = 0;
2182 }
2183 }
2184
2185 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002186 db.beginTransaction();
2187 try {
Adam Cohen72960972014-01-15 18:13:55 -08002188 for (ContentValues row: allItems) {
2189 if (row == null) continue;
2190 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002191 < 0) {
2192 return;
2193 } else {
2194 count++;
2195 }
2196 }
2197 db.setTransactionSuccessful();
2198 } finally {
2199 db.endTransaction();
2200 }
2201 }
2202
2203 db.beginTransaction();
2204 try {
2205 for (i=0; i<=curScreen; i++) {
2206 final ContentValues values = new ContentValues();
2207 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2208 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2209 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2210 < 0) {
2211 return;
2212 }
2213 }
2214 db.setTransactionSuccessful();
2215 } finally {
2216 db.endTransaction();
2217 }
2218 }
2219 } finally {
2220 c.close();
2221 }
2222 }
2223
2224 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2225 + (curScreen+1) + " screens", true);
2226
2227 // ensure that new screens are created to hold these icons
2228 setFlagJustLoadedOldDb();
2229
2230 // Update max IDs; very important since we just grabbed IDs from another database
2231 mMaxItemId = initializeMaxItemId(db);
2232 mMaxScreenId = initializeMaxScreenId(db);
2233 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2234 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002235 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002236
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002237 /**
2238 * Build a query string that will match any row where the column matches
2239 * anything in the values list.
2240 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002241 private static String buildOrWhereString(String column, int[] values) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002242 StringBuilder selectWhere = new StringBuilder();
2243 for (int i = values.length - 1; i >= 0; i--) {
2244 selectWhere.append(column).append("=").append(values[i]);
2245 if (i > 0) {
2246 selectWhere.append(" OR ");
2247 }
2248 }
2249 return selectWhere.toString();
2250 }
2251
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002252 /**
2253 * Return attribute value, attempting launcher-specific namespace first
2254 * before falling back to anonymous attribute.
2255 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002256 private static String getAttributeValue(XmlResourceParser parser, String attribute) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002257 String value = parser.getAttributeValue(
2258 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2259 if (value == null) {
2260 value = parser.getAttributeValue(null, attribute);
2261 }
2262 return value;
2263 }
2264
2265 /**
2266 * Return attribute resource value, attempting launcher-specific namespace
2267 * first before falling back to anonymous attribute.
2268 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002269 private static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002270 int defaultValue) {
2271 int value = parser.getAttributeResourceValue(
2272 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2273 defaultValue);
2274 if (value == defaultValue) {
2275 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2276 }
2277 return value;
2278 }
2279
2280 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2281 to.put(key, from.getAsInteger(key));
2282 }
2283
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002284 static class SqlArguments {
2285 public final String table;
2286 public final String where;
2287 public final String[] args;
2288
2289 SqlArguments(Uri url, String where, String[] args) {
2290 if (url.getPathSegments().size() == 1) {
2291 this.table = url.getPathSegments().get(0);
2292 this.where = where;
2293 this.args = args;
2294 } else if (url.getPathSegments().size() != 2) {
2295 throw new IllegalArgumentException("Invalid URI: " + url);
2296 } else if (!TextUtils.isEmpty(where)) {
2297 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2298 } else {
2299 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002300 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002301 this.args = null;
2302 }
2303 }
2304
2305 SqlArguments(Uri url) {
2306 if (url.getPathSegments().size() == 1) {
2307 table = url.getPathSegments().get(0);
2308 where = null;
2309 args = null;
2310 } else {
2311 throw new IllegalArgumentException("Invalid URI: " + url);
2312 }
2313 }
2314 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002315
2316 static interface WorkspaceLoader {
2317 /**
2318 * @param screenIds A mutable list of screen its
2319 * @return the number of workspace items added.
2320 */
2321 int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds);
2322 }
2323
2324 private static class SimpleWorkspaceLoader implements WorkspaceLoader {
2325 private final Resources mRes;
2326 private final int mWorkspaceId;
2327 private final DatabaseHelper mHelper;
2328
2329 SimpleWorkspaceLoader(DatabaseHelper helper, Resources res, int workspaceId) {
2330 mHelper = helper;
2331 mRes = res;
2332 mWorkspaceId = workspaceId;
2333 }
2334
2335 @Override
2336 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
2337 return mHelper.loadFavoritesRecursive(db, mRes, mWorkspaceId, screenIds);
2338 }
2339 }
Adam Cohen72960972014-01-15 18:13:55 -08002340}