blob: af655367a5c84ef6e4fd90caa21c4921214ac3dd [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
76 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070077
Kenny Guyed131872014-04-30 03:02:21 +010078 private static final int DATABASE_VERSION = 20;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Adam Cohene25af792013-06-06 23:08:25 -070080 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040081 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070082
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050083 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050084 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050085
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070087 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070089 static final String UPGRADED_FROM_OLD_DATABASE =
90 "UPGRADED_FROM_OLD_DATABASE";
91 static final String EMPTY_DATABASE_CREATED =
92 "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Winson Chungb3302ae2012-05-01 10:19:14 -070094 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070095 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070096
Adam Cohena043fa82014-07-23 14:49:38 -070097 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
98
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 private LauncherProviderChangeListener mListener;
100
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700101 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700102 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700103 * {@link AppWidgetHost#deleteHost()} is called during database creation.
104 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
105 */
106 static final Uri CONTENT_APPWIDGET_RESET_URI =
107 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700108
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700109 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700110 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
112 @Override
113 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400114 final Context context = getContext();
115 mOpenHelper = new DatabaseHelper(context);
116 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800117 return true;
118 }
119
Winson Chung0b560dd2014-01-21 13:00:26 -0800120 public boolean wasNewDbCreated() {
121 return mOpenHelper.wasNewDbCreated();
122 }
123
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700124 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
125 mListener = listener;
126 }
127
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 @Override
129 public String getType(Uri uri) {
130 SqlArguments args = new SqlArguments(uri, null, null);
131 if (TextUtils.isEmpty(args.where)) {
132 return "vnd.android.cursor.dir/" + args.table;
133 } else {
134 return "vnd.android.cursor.item/" + args.table;
135 }
136 }
137
138 @Override
139 public Cursor query(Uri uri, String[] projection, String selection,
140 String[] selectionArgs, String sortOrder) {
141
142 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
143 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
144 qb.setTables(args.table);
145
Romain Guy73b979d2009-06-09 12:57:21 -0700146 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800147 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
148 result.setNotificationUri(getContext().getContentResolver(), uri);
149
150 return result;
151 }
152
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153 private static long dbInsertAndCheck(DatabaseHelper helper,
154 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500155 if (values == null) {
156 throw new RuntimeException("Error: attempting to insert null values");
157 }
Adam Cohen71483f42014-05-15 14:04:01 -0700158 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159 throw new RuntimeException("Error: attempting to add item without specifying an id");
160 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500161 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 return db.insert(table, nullColumnHack, values);
163 }
164
Adam Cohen228da5a2011-07-27 22:23:47 -0700165 private static void deleteId(SQLiteDatabase db, long id) {
166 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
167 SqlArguments args = new SqlArguments(uri, null, null);
168 db.delete(args.table, args.where, args.args);
169 }
170
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171 @Override
172 public Uri insert(Uri uri, ContentValues initialValues) {
173 SqlArguments args = new SqlArguments(uri);
174
Adam Cohena043fa82014-07-23 14:49:38 -0700175 // In very limited cases, we support system|signature permission apps to add to the db
176 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
177 if (externalAdd != null && "true".equals(externalAdd)) {
178 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
179 return null;
180 }
181 }
182
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400184 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700185 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186 if (rowId <= 0) return null;
187
188 uri = ContentUris.withAppendedId(uri, rowId);
189 sendNotify(uri);
190
191 return uri;
192 }
193
Adam Cohena043fa82014-07-23 14:49:38 -0700194
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 @Override
196 public int bulkInsert(Uri uri, ContentValues[] values) {
197 SqlArguments args = new SqlArguments(uri);
198
199 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
200 db.beginTransaction();
201 try {
202 int numValues = values.length;
203 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400204 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700205 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
206 return 0;
207 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208 }
209 db.setTransactionSuccessful();
210 } finally {
211 db.endTransaction();
212 }
213
214 sendNotify(uri);
215 return values.length;
216 }
217
218 @Override
Yura085c8532014-02-11 15:15:29 +0000219 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
220 throws OperationApplicationException {
221 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
222 db.beginTransaction();
223 try {
224 ContentProviderResult[] result = super.applyBatch(operations);
225 db.setTransactionSuccessful();
226 return result;
227 } finally {
228 db.endTransaction();
229 }
230 }
231
232 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 public int delete(Uri uri, String selection, String[] selectionArgs) {
234 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
235
236 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
237 int count = db.delete(args.table, args.where, args.args);
238 if (count > 0) sendNotify(uri);
239
240 return count;
241 }
242
243 @Override
244 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
245 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
246
Chris Wren1ada10d2013-09-13 18:01:38 -0400247 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
249 int count = db.update(args.table, values, args.where, args.args);
250 if (count > 0) sendNotify(uri);
251
252 return count;
253 }
254
255 private void sendNotify(Uri uri) {
256 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
257 if (notify == null || "true".equals(notify)) {
258 getContext().getContentResolver().notifyChange(uri, null);
259 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400260
261 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400262 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700263 if (mListener != null) {
264 mListener.onLauncherProviderChange();
265 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400266 }
267
268 private void addModifiedTime(ContentValues values) {
269 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800270 }
271
Adam Cohendcd297f2013-06-18 13:13:40 -0700272 public long generateNewItemId() {
273 return mOpenHelper.generateNewItemId();
274 }
275
Winson Chungc763c4e2013-07-19 13:49:06 -0700276 public void updateMaxItemId(long id) {
277 mOpenHelper.updateMaxItemId(id);
278 }
279
Adam Cohendcd297f2013-06-18 13:13:40 -0700280 public long generateNewScreenId() {
281 return mOpenHelper.generateNewScreenId();
282 }
283
284 // This is only required one time while loading the workspace during the
285 // upgrade path, and should never be called from anywhere else.
286 public void updateMaxScreenId(long maxScreenId) {
287 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700288 }
289
Brian Muramatsu5524b492012-10-02 16:55:54 -0700290 /**
Adam Cohene25af792013-06-06 23:08:25 -0700291 * @param Should we load the old db for upgrade? first run only.
292 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700293 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400294 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700295 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
296
Winson Chungc763c4e2013-07-19 13:49:06 -0700297 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700298
Winson Chungc763c4e2013-07-19 13:49:06 -0700299 sJustLoadedFromOldDb = false;
300 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700301
302 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700303 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700304 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700305 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700306 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700307 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700308 }
309
310 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700311 * Loads the default workspace based on the following priority scheme:
312 * 1) From a package provided by play store
313 * 2) From a partner configuration APK, already in the system image
314 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700315 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700316 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400317 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700318 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700319
Winson Chungc763c4e2013-07-19 13:49:06 -0700320 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500321 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200322
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700323 WorkspaceLoader loader = AutoInstallsLayout.get(getContext(),
324 mOpenHelper.mAppWidgetHost, mOpenHelper);
325
326 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700327 final Partner partner = Partner.get(getContext().getPackageManager());
328 if (partner != null && partner.hasDefaultLayout()) {
329 final Resources partnerRes = partner.getResources();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700330 int workspaceResId = partnerRes.getIdentifier(Partner.RESOURCE_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700331 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700332 if (workspaceResId != 0) {
333 loader = new SimpleWorkspaceLoader(mOpenHelper, partnerRes, workspaceResId);
334 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700335 }
336 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700337
338 if (loader == null) {
339 loader = new SimpleWorkspaceLoader(mOpenHelper, getContext().getResources(),
340 getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700341 }
342
Michael Jurkab85f8a42012-04-25 15:48:32 -0700343 // Populate favorites table with initial favorites
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700344 SharedPreferences.Editor editor = sp.edit().remove(EMPTY_DATABASE_CREATED);
345 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700346 editor.commit();
347 }
348 }
349
Dan Sandlerd5024042014-01-09 15:01:33 -0500350 public void migrateLauncher2Shortcuts() {
351 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400352 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500353 }
354
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800355 private static int getDefaultWorkspaceResourceId() {
Winson Chungbe876472014-05-14 14:15:20 -0700356 LauncherAppState app = LauncherAppState.getInstance();
357 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800358 if (LauncherAppState.isDisableAllApps()) {
Winson Chungbe876472014-05-14 14:15:20 -0700359 return grid.defaultNoAllAppsLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800360 } else {
Winson Chungbe876472014-05-14 14:15:20 -0700361 return grid.defaultLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800362 }
363 }
364
Winson Chungc763c4e2013-07-19 13:49:06 -0700365 private static interface ContentValuesCallback {
366 public void onRow(ContentValues values);
367 }
368
Adam Cohen6dbe0492013-12-02 17:00:14 -0800369 private static boolean shouldImportLauncher2Database(Context context) {
370 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
371
372 // We don't import the old databse for tablets, as the grid size has changed.
373 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
374 }
375
Dan Sandlerd5024042014-01-09 15:01:33 -0500376 public void deleteDatabase() {
377 // Are you sure? (y/n)
378 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500379 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500380 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500381 if (dbFile.exists()) {
382 SQLiteDatabase.deleteDatabase(dbFile);
383 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500384 mOpenHelper = new DatabaseHelper(getContext());
385 }
386
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700387 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Jason Monk41314972014-03-03 16:11:30 -0500388 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 private static final String TAG_FAVORITES = "favorites";
390 private static final String TAG_FAVORITE = "favorite";
Mike Cleronb87bd162009-10-30 16:36:56 -0700391 private static final String TAG_APPWIDGET = "appwidget";
392 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700393 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700394 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700395 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400396 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700397
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700398 // Style attrs -- "Favorite"
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700399 private static final String ATTR_CLASS_NAME = "className";
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700400 private static final String ATTR_PACKAGE_NAME = "packageName";
401 private static final String ATTR_CONTAINER = "container";
402 private static final String ATTR_SCREEN = "screen";
403 private static final String ATTR_X = "x";
404 private static final String ATTR_Y = "y";
405 private static final String ATTR_SPAN_X = "spanX";
406 private static final String ATTR_SPAN_Y = "spanY";
407 private static final String ATTR_ICON = "icon";
408 private static final String ATTR_TITLE = "title";
409 private static final String ATTR_URI = "uri";
410
411 // Style attrs -- "Include"
412 private static final String ATTR_WORKSPACE = "workspace";
413
414 // Style attrs -- "Extra"
415 private static final String ATTR_KEY = "key";
416 private static final String ATTR_VALUE = "value";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700417
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800418 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700419 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700420 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700421 private long mMaxItemId = -1;
422 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800423
Winson Chung0b560dd2014-01-21 13:00:26 -0800424 private boolean mNewDbCreated = false;
425
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800426 DatabaseHelper(Context context) {
427 super(context, DATABASE_NAME, null, DATABASE_VERSION);
428 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700429 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700430 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700431
432 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
433 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700434 if (mMaxItemId == -1) {
435 mMaxItemId = initializeMaxItemId(getWritableDatabase());
436 }
437 if (mMaxScreenId == -1) {
438 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700439 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800440 }
441
Winson Chung0b560dd2014-01-21 13:00:26 -0800442 public boolean wasNewDbCreated() {
443 return mNewDbCreated;
444 }
445
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700446 /**
447 * Send notification that we've deleted the {@link AppWidgetHost},
448 * probably as part of the initial database creation. The receiver may
449 * want to re-call {@link AppWidgetHost#startListening()} to ensure
450 * callbacks are correctly set.
451 */
452 private void sendAppWidgetResetNotify() {
453 final ContentResolver resolver = mContext.getContentResolver();
454 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
455 }
456
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800457 @Override
458 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800459 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700460
Adam Cohendcd297f2013-06-18 13:13:40 -0700461 mMaxItemId = 1;
462 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800463 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700464
Kenny Guyed131872014-04-30 03:02:21 +0100465 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
466 long userSerialNumber = userManager.getSerialNumberForUser(
467 UserHandleCompat.myUserHandle());
468
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 db.execSQL("CREATE TABLE favorites (" +
470 "_id INTEGER PRIMARY KEY," +
471 "title TEXT," +
472 "intent TEXT," +
473 "container INTEGER," +
474 "screen INTEGER," +
475 "cellX INTEGER," +
476 "cellY INTEGER," +
477 "spanX INTEGER," +
478 "spanY INTEGER," +
479 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700480 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800481 "isShortcut INTEGER," +
482 "iconType INTEGER," +
483 "iconPackage TEXT," +
484 "iconResource TEXT," +
485 "icon BLOB," +
486 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400487 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400488 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500489 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100490 "restored INTEGER NOT NULL DEFAULT 0," +
491 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700493 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700495 // Database was just created, so wipe any previous widgets
496 if (mAppWidgetHost != null) {
497 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700498 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800499 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700500
Adam Cohen6dbe0492013-12-02 17:00:14 -0800501 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500502 // Try converting the old database
503 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
504 public void onRow(ContentValues values) {
505 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
506 if (container == Favorites.CONTAINER_DESKTOP) {
507 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
508 screen = (int) upgradeLauncherDb_permuteScreens(screen);
509 values.put(LauncherSettings.Favorites.SCREEN, screen);
510 }
511 }
512 };
513 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
514 "/old_favorites?notify=true");
515 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
516 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400517 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500518 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
519 // If we fail, then set a flag to load the default workspace
520 setFlagEmptyDbCreated();
521 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700522 }
523 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500524 // Right now, in non-default workspace cases, we want to run the final
525 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
526 // set that flag too.
527 setFlagJustLoadedOldDb();
528 } else {
529 // Fresh and clean launcher DB.
530 mMaxItemId = initializeMaxItemId(db);
531 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800532 }
533 }
534
Adam Cohendcd297f2013-06-18 13:13:40 -0700535 private void addWorkspacesTable(SQLiteDatabase db) {
536 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
537 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400538 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
539 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700540 ");");
541 }
542
Adam Cohen119285e2014-04-02 16:59:08 -0700543 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700544 // Delete items directly on the workspace who's screen id doesn't exist
545 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
546 // AND container = -100"
547 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
548 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700549 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700550 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
551 " AND " +
552 LauncherSettings.Favorites.CONTAINER + " = " +
553 LauncherSettings.Favorites.CONTAINER_DESKTOP;
554 db.execSQL(removeOrphanedDesktopItems);
555
556 // Delete items contained in folders which no longer exist (after above statement)
557 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
558 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
559 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
560 " WHERE " +
561 LauncherSettings.Favorites.CONTAINER + " <> " +
562 LauncherSettings.Favorites.CONTAINER_DESKTOP +
563 " AND "
564 + LauncherSettings.Favorites.CONTAINER + " <> " +
565 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
566 " AND "
567 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
568 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
569 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
570 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
571 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700572 }
573
Winson Chungc763c4e2013-07-19 13:49:06 -0700574 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400575 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700576 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
577 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700578 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
579 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700580 editor.commit();
581 }
582
Winson Chungc763c4e2013-07-19 13:49:06 -0700583 private void setFlagEmptyDbCreated() {
584 String spKey = LauncherAppState.getSharedPreferencesKey();
585 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
586 SharedPreferences.Editor editor = sp.edit();
587 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
588 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
589 editor.commit();
590 }
591
592 // We rearrange the screens from the old launcher
593 // 12345 -> 34512
594 private long upgradeLauncherDb_permuteScreens(long screen) {
595 if (screen >= 2) {
596 return screen - 2;
597 } else {
598 return screen + 3;
599 }
600 }
601
602 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
603 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800604 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 boolean converted = false;
606
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 final ContentResolver resolver = mContext.getContentResolver();
608 Cursor cursor = null;
609
610 try {
611 cursor = resolver.query(uri, null, null, null, null);
612 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700613 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 }
615
616 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700617 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800618 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700619 if (cursor.getCount() > 0) {
620 converted = copyFromCursor(db, cursor, cb) > 0;
621 if (converted && deleteRows) {
622 resolver.delete(uri, null, null);
623 }
624 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625 } finally {
626 cursor.close();
627 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700629
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700631 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800632 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700634
635 // Update max item id
636 mMaxItemId = initializeMaxItemId(db);
637 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 }
639
640 return converted;
641 }
642
Winson Chungc763c4e2013-07-19 13:49:06 -0700643 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700644 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
646 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
647 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
648 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
649 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
650 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
651 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
652 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
653 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
654 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
655 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
656 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
657 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
658
659 ContentValues[] rows = new ContentValues[c.getCount()];
660 int i = 0;
661 while (c.moveToNext()) {
662 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700663 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
665 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
666 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
667 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
668 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
669 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
670 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
671 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700672 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800673 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
674 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
675 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
676 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
677 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700678 if (cb != null) {
679 cb.onRow(values);
680 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 rows[i++] = values;
682 }
683
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700685 if (i > 0) {
686 db.beginTransaction();
687 try {
688 int numValues = rows.length;
689 for (i = 0; i < numValues; i++) {
690 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
691 return 0;
692 } else {
693 total++;
694 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800695 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700696 db.setTransactionSuccessful();
697 } finally {
698 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800700 }
701
702 return total;
703 }
704
705 @Override
706 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700707 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700708
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800709 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700710 if (version < 3) {
711 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800712 db.beginTransaction();
713 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700714 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800715 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700716 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800717 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700718 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800719 } catch (SQLException ex) {
720 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800721 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800722 } finally {
723 db.endTransaction();
724 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700725
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800726 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700727 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800728 convertWidgets(db);
729 }
730 }
Romain Guy73b979d2009-06-09 12:57:21 -0700731
732 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800733 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700734 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700735
Romain Guy509cd6a2010-03-23 15:10:56 -0700736 // Where's version 5?
737 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400738 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700739 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
740 // but version 5 on there was the updateContactsShortcuts change
741 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
742 // The updateContactsShortcuts change is idempotent, so running it twice
743 // is okay so we'll do that when upgrading the devices that shipped with it.
744 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800745 // We went from 3 to 5 screens. Move everything 1 to the right
746 db.beginTransaction();
747 try {
748 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
749 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800750 } catch (SQLException ex) {
751 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800752 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800753 } finally {
754 db.endTransaction();
755 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700756
Romain Guy509cd6a2010-03-23 15:10:56 -0700757 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800758 if (updateContactsShortcuts(db)) {
759 version = 6;
760 }
761 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000762
763 if (version < 7) {
764 // Version 7 gets rid of the special search widget.
765 convertWidgets(db);
766 version = 7;
767 }
768
Joe Onorato0589f0f2010-02-08 13:44:00 -0800769 if (version < 8) {
770 // Version 8 (froyo) has the icons all normalized. This should
771 // already be the case in practice, but we now rely on it and don't
772 // resample the images each time.
773 normalizeIcons(db);
774 version = 8;
775 }
776
Winson Chung3d503fb2011-07-13 17:25:49 -0700777 if (version < 9) {
778 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
779 // 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 -0700780 if (mMaxItemId == -1) {
781 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700782 }
783
784 // Add default hotseat icons
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700785 loadFavorites(db, new SimpleWorkspaceLoader(this, mContext.getResources(),
786 R.xml.update_workspace));
Winson Chung3d503fb2011-07-13 17:25:49 -0700787 version = 9;
788 }
789
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700790 // We bumped the version three time during JB, once to update the launch flags, once to
791 // update the override for the default launch animation and once to set the mimetype
792 // to improve startup performance
793 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700794 // Contact shortcuts need a different set of flags to be launched now
795 // The updateContactsShortcuts change is idempotent, so we can keep using it like
796 // back in the Donut days
797 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700798 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700799 }
800
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 if (version < 13) {
802 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
803 // to persist workspace screens and their relative order.
804 mMaxScreenId = 0;
805
806 // This will never happen in the wild, but when we switch to using workspace
807 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700808 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700809
810 addWorkspacesTable(db);
811 version = 13;
812 }
813
Chris Wrend5e66bf2013-09-16 14:02:29 -0400814 if (version < 14) {
815 db.beginTransaction();
816 try {
817 // Insert new column for holding widget provider name
818 db.execSQL("ALTER TABLE favorites " +
819 "ADD COLUMN appWidgetProvider TEXT;");
820 db.setTransactionSuccessful();
821 version = 14;
822 } catch (SQLException ex) {
823 // Old version remains, which means we wipe old data
824 Log.e(TAG, ex.getMessage(), ex);
825 } finally {
826 db.endTransaction();
827 }
828 }
829
Chris Wren1ada10d2013-09-13 18:01:38 -0400830 if (version < 15) {
831 db.beginTransaction();
832 try {
833 // Insert new column for holding update timestamp
834 db.execSQL("ALTER TABLE favorites " +
835 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
836 db.execSQL("ALTER TABLE workspaceScreens " +
837 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
838 db.setTransactionSuccessful();
839 version = 15;
840 } catch (SQLException ex) {
841 // Old version remains, which means we wipe old data
842 Log.e(TAG, ex.getMessage(), ex);
843 } finally {
844 db.endTransaction();
845 }
846 }
847
Chris Wrenf4d08112014-01-16 18:13:56 -0500848
849 if (version < 16) {
850 db.beginTransaction();
851 try {
852 // Insert new column for holding restore status
853 db.execSQL("ALTER TABLE favorites " +
854 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
855 db.setTransactionSuccessful();
856 version = 16;
857 } catch (SQLException ex) {
858 // Old version remains, which means we wipe old data
859 Log.e(TAG, ex.getMessage(), ex);
860 } finally {
861 db.endTransaction();
862 }
863 }
864
Adam Cohen71e03b92014-02-21 14:09:53 -0800865 if (version < 17) {
866 // We use the db version upgrade here to identify users who may not have seen
867 // clings yet (because they weren't available), but for whom the clings are now
868 // available (tablet users). Because one of the possible cling flows (migration)
869 // is very destructive (wipes out workspaces), we want to prevent this from showing
870 // until clear data. We do so by marking that the clings have been shown.
871 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
872 version = 17;
873 }
874
Adam Cohen119285e2014-04-02 16:59:08 -0700875 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700876 // No-op
877 version = 18;
878 }
879
880 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700881 // Due to a data loss bug, some users may have items associated with screen ids
882 // which no longer exist. Since this can cause other problems, and since the user
883 // will never see these items anyway, we use database upgrade as an opportunity to
884 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700885 removeOrphanedItems(db);
886 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700887 }
888
Kenny Guyed131872014-04-30 03:02:21 +0100889 if (version < 20) {
890 // Add userId column
891 if (addProfileColumn(db)) {
892 version = 20;
893 }
894 // else old version remains, which means we wipe old data
895 }
896
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800897 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800898 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800899 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700900 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
901
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800902 onCreate(db);
903 }
904 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800905
Adam Cohen9b1d0622014-05-21 19:01:57 -0700906 @Override
907 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
908 // This shouldn't happen -- throw our hands up in the air and start over.
909 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
910 ". Wiping databse.");
911
912 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
913 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
914 onCreate(db);
915 }
916
Kenny Guyed131872014-04-30 03:02:21 +0100917 private boolean addProfileColumn(SQLiteDatabase db) {
918 db.beginTransaction();
919 try {
920 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
921 // Default to the serial number of this user, for older
922 // shortcuts.
923 long userSerialNumber = userManager.getSerialNumberForUser(
924 UserHandleCompat.myUserHandle());
925 // Insert new column for holding user serial number
926 db.execSQL("ALTER TABLE favorites " +
927 "ADD COLUMN profileId INTEGER DEFAULT "
928 + userSerialNumber + ";");
929 db.setTransactionSuccessful();
930 } catch (SQLException ex) {
931 // Old version remains, which means we wipe old data
932 Log.e(TAG, ex.getMessage(), ex);
933 return false;
934 } finally {
935 db.endTransaction();
936 }
937 return true;
938 }
939
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800940 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800941 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
942 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
943
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700944 Cursor c = null;
945 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800946 db.beginTransaction();
947 try {
948 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700949 c = db.query(TABLE_FAVORITES,
950 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800951 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700952 if (c == null) return false;
953
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800954 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700955
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800956 final int idIndex = c.getColumnIndex(Favorites._ID);
957 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700958
959 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800960 long favoriteId = c.getLong(idIndex);
961 final String intentUri = c.getString(intentIndex);
962 if (intentUri != null) {
963 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700964 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800965 android.util.Log.d("Home", intent.toString());
966 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700967 if (uri != null) {
968 final String data = uri.toString();
969 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
970 actionQuickContact.equals(intent.getAction())) &&
971 (data.startsWith("content://contacts/people/") ||
972 data.startsWith("content://com.android.contacts/" +
973 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800974
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700975 final Intent newIntent = new Intent(actionQuickContact);
976 // When starting from the launcher, start in a new, cleared task
977 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
978 // clear the whole thing preemptively here since
979 // QuickContactActivity will finish itself when launching other
980 // detail activities.
981 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
982 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700983 newIntent.putExtra(
984 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700985 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700986 // Determine the type and also put that in the shortcut
987 // (that can speed up launch a bit)
988 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800989
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700990 final ContentValues values = new ContentValues();
991 values.put(LauncherSettings.Favorites.INTENT,
992 newIntent.toUri(0));
993
994 String updateWhere = Favorites._ID + "=" + favoriteId;
995 db.update(TABLE_FAVORITES, values, updateWhere, null);
996 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800997 }
998 } catch (RuntimeException ex) {
999 Log.e(TAG, "Problem upgrading shortcut", ex);
1000 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001001 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001002 }
1003 }
1004 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001005
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001006 db.setTransactionSuccessful();
1007 } catch (SQLException ex) {
1008 Log.w(TAG, "Problem while upgrading contacts", ex);
1009 return false;
1010 } finally {
1011 db.endTransaction();
1012 if (c != null) {
1013 c.close();
1014 }
1015 }
1016
1017 return true;
1018 }
1019
Joe Onorato0589f0f2010-02-08 13:44:00 -08001020 private void normalizeIcons(SQLiteDatabase db) {
1021 Log.d(TAG, "normalizing icons");
1022
Joe Onorato346e1292010-02-18 10:34:24 -05001023 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001024 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -04001025 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001026 try {
1027 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -04001028 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -06001029 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -08001030
1031 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
1032 Favorites.ICON_TYPE_BITMAP, null);
1033
1034 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1035 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
1036
1037 while (c.moveToNext()) {
1038 long id = c.getLong(idIndex);
1039 byte[] data = c.getBlob(iconIndex);
1040 try {
1041 Bitmap bitmap = Utilities.resampleIconBitmap(
1042 BitmapFactory.decodeByteArray(data, 0, data.length),
1043 mContext);
1044 if (bitmap != null) {
1045 update.bindLong(1, id);
1046 data = ItemInfo.flattenBitmap(bitmap);
1047 if (data != null) {
1048 update.bindBlob(2, data);
1049 update.execute();
1050 }
1051 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001052 }
1053 } catch (Exception e) {
1054 if (!logged) {
1055 Log.e(TAG, "Failed normalizing icon " + id, e);
1056 } else {
1057 Log.e(TAG, "Also failed normalizing icon " + id);
1058 }
1059 logged = true;
1060 }
1061 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001062 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001063 } catch (SQLException ex) {
1064 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1065 } finally {
1066 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001067 if (update != null) {
1068 update.close();
1069 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001070 if (c != null) {
1071 c.close();
1072 }
1073 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001074 }
1075
1076 // Generates a new ID to use for an object in your database. This method should be only
1077 // called from the main UI thread. As an exception, we do call it when we call the
1078 // constructor from the worker thread; however, this doesn't extend until after the
1079 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1080 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001081 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001082 public long generateNewItemId() {
1083 if (mMaxItemId < 0) {
1084 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001085 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001086 mMaxItemId += 1;
1087 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001088 }
1089
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001090 @Override
1091 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
1092 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
1093 }
1094
Winson Chungc763c4e2013-07-19 13:49:06 -07001095 public void updateMaxItemId(long id) {
1096 mMaxItemId = id + 1;
1097 }
1098
Chris Wren5dee7af2013-12-20 17:22:11 -05001099 public void checkId(String table, ContentValues values) {
1100 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1101 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1102 mMaxScreenId = Math.max(id, mMaxScreenId);
1103 } else {
1104 mMaxItemId = Math.max(id, mMaxItemId);
1105 }
1106 }
1107
Adam Cohendcd297f2013-06-18 13:13:40 -07001108 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001109 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1110
1111 // get the result
1112 final int maxIdIndex = 0;
1113 long id = -1;
1114 if (c != null && c.moveToNext()) {
1115 id = c.getLong(maxIdIndex);
1116 }
Michael Jurka5130e402011-10-13 04:55:35 -07001117 if (c != null) {
1118 c.close();
1119 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001120
1121 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001122 throw new RuntimeException("Error: could not query max item id");
1123 }
1124
1125 return id;
1126 }
1127
1128 // Generates a new ID to use for an workspace screen in your database. This method
1129 // should be only called from the main UI thread. As an exception, we do call it when we
1130 // call the constructor from the worker thread; however, this doesn't extend until after the
1131 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1132 // after that point
1133 public long generateNewScreenId() {
1134 if (mMaxScreenId < 0) {
1135 throw new RuntimeException("Error: max screen id was not initialized");
1136 }
1137 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001138 // Log to disk
1139 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 return mMaxScreenId;
1141 }
1142
1143 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001144 // Log to disk
1145 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001146 mMaxScreenId = maxScreenId;
1147 }
1148
1149 private long initializeMaxScreenId(SQLiteDatabase db) {
1150 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1151
1152 // get the result
1153 final int maxIdIndex = 0;
1154 long id = -1;
1155 if (c != null && c.moveToNext()) {
1156 id = c.getLong(maxIdIndex);
1157 }
1158 if (c != null) {
1159 c.close();
1160 }
1161
1162 if (id == -1) {
1163 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001164 }
1165
Winson Chunga90303b2013-11-15 13:05:06 -08001166 // Log to disk
1167 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001168 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001169 }
1170
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001172 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001173 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001174 */
1175 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001176 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001177 final int[] bindSources = new int[] {
1178 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1179 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001180 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001182
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001183 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001184
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001185 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001186
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001187 db.beginTransaction();
1188 try {
1189 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001190 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001191 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001192
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001193 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001194
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001195 final ContentValues values = new ContentValues();
1196 while (c != null && c.moveToNext()) {
1197 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001198 int favoriteType = c.getInt(1);
1199
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001200 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001201 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001202 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001203
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001204 if (LOGD) {
1205 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1206 + " for favoriteId=" + favoriteId);
1207 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001209 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1210 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1211
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001212 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001213 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1214 values.put(LauncherSettings.Favorites.SPANX, 4);
1215 values.put(LauncherSettings.Favorites.SPANY, 1);
1216 } else {
1217 values.put(LauncherSettings.Favorites.SPANX, 2);
1218 values.put(LauncherSettings.Favorites.SPANY, 2);
1219 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001220
1221 String updateWhere = Favorites._ID + "=" + favoriteId;
1222 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001223
Bjorn Bringert34251342009-12-15 13:33:11 +00001224 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001225 // TODO: check return value
1226 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001227 new ComponentName("com.android.alarmclock",
1228 "com.android.alarmclock.AnalogAppWidgetProvider"));
1229 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001230 // TODO: check return value
1231 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001232 new ComponentName("com.android.camera",
1233 "com.android.camera.PhotoAppWidgetProvider"));
1234 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001235 // TODO: check return value
1236 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001237 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001238 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001239 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001240 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001241 }
1242 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001243
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001244 db.setTransactionSuccessful();
1245 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001246 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001247 } finally {
1248 db.endTransaction();
1249 if (c != null) {
1250 c.close();
1251 }
1252 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001253
1254 // Update max item id
1255 mMaxItemId = initializeMaxItemId(db);
1256 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001257 }
1258
Adam Cohena043fa82014-07-23 14:49:38 -07001259 private boolean initializeExternalAdd(ContentValues values) {
1260 // 1. Ensure that externally added items have a valid item id
1261 long id = generateNewItemId();
1262 values.put(LauncherSettings.Favorites._ID, id);
1263
1264 // 2. In the case of an app widget, and if no app widget id is specified, we
1265 // attempt allocate and bind the widget.
1266 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1267 if (itemType != null &&
1268 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1269 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1270
1271 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1272 ComponentName cn = ComponentName.unflattenFromString(
1273 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1274
1275 if (cn != null) {
1276 try {
1277 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001278 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
1279 if (appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
1280 return true;
Adam Cohena043fa82014-07-23 14:49:38 -07001281 }
1282 } catch (RuntimeException e) {
1283 Log.e(TAG, "Failed to initialize external widget", e);
Adam Cohena043fa82014-07-23 14:49:38 -07001284 }
1285 }
Adam Cohen3ed316a2014-07-23 18:21:20 -07001286 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001287 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001288
1289 // Add screen id if not present
1290 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1291 if (!addScreenIdIfNecessary(screenId)) {
1292 return false;
1293 }
Adam Cohena043fa82014-07-23 14:49:38 -07001294 return true;
1295 }
1296
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001297 // Returns true of screen id exists, or if successfully added
1298 private boolean addScreenIdIfNecessary(long screenId) {
1299 if (!hasScreenId(screenId)) {
1300 int rank = getMaxScreenRank() + 1;
1301
1302 ContentValues v = new ContentValues();
1303 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1304 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1305 if (dbInsertAndCheck(this, getWritableDatabase(),
1306 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1307 return false;
1308 }
1309 }
1310 return true;
1311 }
1312
1313 private boolean hasScreenId(long screenId) {
1314 SQLiteDatabase db = getWritableDatabase();
1315 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1316 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1317 if (c != null) {
1318 int count = c.getCount();
1319 c.close();
1320 return count > 0;
1321 } else {
1322 return false;
1323 }
1324 }
1325
1326 private int getMaxScreenRank() {
1327 SQLiteDatabase db = getWritableDatabase();
1328 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1329 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1330
1331 // get the result
1332 final int maxRankIndex = 0;
1333 int rank = -1;
1334 if (c != null && c.moveToNext()) {
1335 rank = c.getInt(maxRankIndex);
1336 }
1337 if (c != null) {
1338 c.close();
1339 }
1340
1341 return rank;
1342 }
1343
Michael Jurka8b805b12012-04-18 14:23:14 -07001344 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1345 throws XmlPullParserException, IOException {
1346 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001347 while ((type = parser.next()) != XmlPullParser.START_TAG
1348 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001349 ;
1350 }
1351
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001352 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001353 throw new XmlPullParserException("No start tag found");
1354 }
1355
1356 if (!parser.getName().equals(firstElementName)) {
1357 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1358 ", expected " + firstElementName);
1359 }
1360 }
1361
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001362 private static Intent buildMainIntent() {
1363 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1364 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1365 return intent;
1366 }
1367
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001368 private int loadFavorites(SQLiteDatabase db, WorkspaceLoader loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001369 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001370 // TODO: Use multiple loaders with fall-back and transaction.
1371 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001372
1373 // Add the screens specified by the items above
1374 Collections.sort(screenIds);
1375 int rank = 0;
1376 ContentValues values = new ContentValues();
1377 for (Long id : screenIds) {
1378 values.clear();
1379 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1380 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1381 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1382 throw new RuntimeException("Failed initialize screen table"
1383 + "from default layout");
1384 }
1385 rank++;
1386 }
1387
1388 // Ensure that the max ids are initialized
1389 mMaxItemId = initializeMaxItemId(db);
1390 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001391
Adam Cohen71483f42014-05-15 14:04:01 -07001392 return count;
1393 }
1394
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001395 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001396 * Loads the default set of favorite packages from an xml file.
1397 *
1398 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001399 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001400 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001401 */
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001402 private int loadFavoritesRecursive(SQLiteDatabase db, Resources res, int workspaceResourceId,
Adam Cohen71483f42014-05-15 14:04:01 -07001403 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001404
Adam Cohen71483f42014-05-15 14:04:01 -07001405 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001406 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1407
Adam Cohen71483f42014-05-15 14:04:01 -07001408 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001409 try {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001410 XmlResourceParser parser = res.getXml(workspaceResourceId);
Michael Jurka8b805b12012-04-18 14:23:14 -07001411 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001412
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001413 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001414
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001415 int type;
1416 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1417 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1418
1419 if (type != XmlPullParser.START_TAG) {
1420 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001421 }
1422
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001423 boolean added = false;
1424 final String name = parser.getName();
1425
Daniel Sandler57dac262013-10-03 13:28:36 -04001426 if (TAG_INCLUDE.equals(name)) {
Daniel Sandler57dac262013-10-03 13:28:36 -04001427
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001428 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
Daniel Sandler57dac262013-10-03 13:28:36 -04001429
1430 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1431 "", resId));
1432
1433 if (resId != 0 && resId != workspaceResourceId) {
1434 // recursively load some more favorites, why not?
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001435 count += loadFavoritesRecursive(db, res, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001436 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001437 } else {
1438 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1439 }
1440
Daniel Sandler57dac262013-10-03 13:28:36 -04001441 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1442 continue;
1443 }
1444
1445 // Assuming it's a <favorite> at this point
Winson Chung3d503fb2011-07-13 17:25:49 -07001446 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001447 String strContainer = getAttributeValue(parser, ATTR_CONTAINER);
1448 if (strContainer != null) {
1449 container = Long.valueOf(strContainer);
Winson Chung3d503fb2011-07-13 17:25:49 -07001450 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001451
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001452 String screen = getAttributeValue(parser, ATTR_SCREEN);
1453 String x = getAttributeValue(parser, ATTR_X);
1454 String y = getAttributeValue(parser, ATTR_Y);
Winson Chung6d092682011-11-16 18:43:26 -08001455
Winson Chung6d092682011-11-16 18:43:26 -08001456 values.clear();
1457 values.put(LauncherSettings.Favorites.CONTAINER, container);
1458 values.put(LauncherSettings.Favorites.SCREEN, screen);
1459 values.put(LauncherSettings.Favorites.CELLX, x);
1460 values.put(LauncherSettings.Favorites.CELLY, y);
1461
Daniel Sandler57dac262013-10-03 13:28:36 -04001462 if (LOGD) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001463 final String title = getAttributeValue(parser, ATTR_TITLE);
1464 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
Daniel Sandler57dac262013-10-03 13:28:36 -04001465 final String something = title != null ? title : pkg;
1466 Log.v(TAG, String.format(
1467 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1468 "", name,
1469 (something == null ? "" : (" \"" + something + "\"")),
1470 container, screen, x, y));
1471 }
1472
Winson Chung6d092682011-11-16 18:43:26 -08001473 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001474 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001475 added = id >= 0;
Winson Chung6d092682011-11-16 18:43:26 -08001476 } else if (TAG_APPWIDGET.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001477 added = addAppWidget(parser, type, db, values);
Winson Chung6d092682011-11-16 18:43:26 -08001478 } else if (TAG_SHORTCUT.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001479 long id = addUriShortcut(db, values, res, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001480 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001481 } else if (TAG_RESOLVE.equals(name)) {
1482 // This looks through the contained favorites (or meta-favorites) and
1483 // attempts to add them as shortcuts in the fallback group's location
1484 // until one is added successfully.
1485 added = false;
1486 final int groupDepth = parser.getDepth();
1487 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1488 parser.getDepth() > groupDepth) {
1489 if (type != XmlPullParser.START_TAG) {
1490 continue;
1491 }
1492 final String fallback_item_name = parser.getName();
Jason Monk41314972014-03-03 16:11:30 -05001493 if (!added) {
1494 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001495 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001496 added = id >= 0;
1497 } else {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001498 Log.e(TAG, "Fallback groups can contain only favorites, found "
1499 + fallback_item_name);
Jason Monk41314972014-03-03 16:11:30 -05001500 }
1501 }
Jason Monk41314972014-03-03 16:11:30 -05001502 }
Winson Chung6d092682011-11-16 18:43:26 -08001503 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001504 // Folder contents are nested in this XML file
Adam Cohen43f3ca02014-07-25 13:24:09 -07001505 added = loadFolder(db, values, res, parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001506
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001507 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1508 // Folder contents come from an external XML resource
1509 final Partner partner = Partner.get(mPackageManager);
1510 if (partner != null) {
1511 final Resources partnerRes = partner.getResources();
1512 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1513 "xml", partner.getPackageName());
1514 if (resId != 0) {
1515 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1516 beginDocument(partnerParser, TAG_FOLDER);
1517 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001518 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001519 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001520 }
Adam Cohen71483f42014-05-15 14:04:01 -07001521 if (added) {
1522 long screenId = Long.parseLong(screen);
1523 // Keep track of the set of screens which need to be added to the db.
1524 if (!screenIds.contains(screenId) &&
1525 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1526 screenIds.add(screenId);
1527 }
1528 count++;
1529 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001530 }
1531 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001532 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001533 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001534 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001535 } catch (RuntimeException e) {
1536 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001537 }
Adam Cohen71483f42014-05-15 14:04:01 -07001538 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001539 }
1540
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001541 /**
1542 * Parse folder starting at current {@link XmlPullParser} location.
1543 */
1544 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1545 XmlResourceParser parser) throws IOException, XmlPullParserException {
1546 final String title;
1547 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1548 if (titleResId != 0) {
1549 title = res.getString(titleResId);
1550 } else {
1551 title = mContext.getResources().getString(R.string.folder_name);
1552 }
1553
1554 values.put(LauncherSettings.Favorites.TITLE, title);
1555 long folderId = addFolder(db, values);
1556 boolean added = folderId >= 0;
1557
1558 ArrayList<Long> folderItems = new ArrayList<Long>();
1559
1560 int type;
1561 int folderDepth = parser.getDepth();
1562 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1563 parser.getDepth() > folderDepth) {
1564 if (type != XmlPullParser.START_TAG) {
1565 continue;
1566 }
1567 final String tag = parser.getName();
1568
1569 final ContentValues childValues = new ContentValues();
1570 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1571
1572 if (LOGD) {
1573 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1574 final String uri = getAttributeValue(parser, ATTR_URI);
1575 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1576 tag, uri != null ? uri : pkg));
1577 }
1578
1579 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1580 final long id = addAppShortcut(db, childValues, parser);
1581 if (id >= 0) {
1582 folderItems.add(id);
1583 }
1584 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1585 final long id = addUriShortcut(db, childValues, res, parser);
1586 if (id >= 0) {
1587 folderItems.add(id);
1588 }
1589 } else {
1590 throw new RuntimeException("Folders can contain only shortcuts");
1591 }
1592 }
1593
1594 // We can only have folders with >= 2 items, so we need to remove the
1595 // folder and clean up if less than 2 items were included, or some
1596 // failed to add, and less than 2 were actually added
1597 if (folderItems.size() < 2 && folderId >= 0) {
1598 // Delete the folder
1599 deleteId(db, folderId);
1600
1601 // If we have a single item, promote it to where the folder
1602 // would have been.
1603 if (folderItems.size() == 1) {
1604 final ContentValues childValues = new ContentValues();
1605 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1606 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1607 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1608 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1609
1610 final long id = folderItems.get(0);
1611 db.update(TABLE_FAVORITES, childValues,
1612 LauncherSettings.Favorites._ID + "=" + id, null);
1613 } else {
1614 added = false;
1615 }
1616 }
1617 return added;
1618 }
1619
Jason Monk41314972014-03-03 16:11:30 -05001620 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1621 // logical choice for what shortcut should be used for that intent exists, then it is
1622 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001623 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1624 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001625 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001626 try {
Jason Monk41314972014-03-03 16:11:30 -05001627 metaIntent = Intent.parseUri(intentUri, 0);
1628 } catch (URISyntaxException e) {
1629 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1630 return -1;
1631 }
1632
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001633 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001634 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001635 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001636 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1637
1638 // Verify that the result is an app and not just the resolver dialog asking which
1639 // app to use.
1640 if (wouldLaunchResolverActivity(resolved, appList)) {
1641 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001642 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001643 if (systemApp == null) {
1644 // There is no logical choice for this meta-favorite, so rather than making
1645 // a bad choice just add nothing.
1646 Log.w(TAG, "No preference or single system activity found for "
1647 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001648 return -1;
1649 }
Jason Monk41314972014-03-03 16:11:30 -05001650 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001651 }
Jason Monk41314972014-03-03 16:11:30 -05001652 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001653 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001654 intent.setComponent(new ComponentName(info.packageName, info.name));
1655 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1656 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1657
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001658 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001659 }
1660
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001661 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001662 ResolveInfo systemResolve = null;
1663 final int N = appList.size();
1664 for (int i = 0; i < N; ++i) {
1665 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001666 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001667 appList.get(i).activityInfo.packageName, 0);
1668 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1669 if (systemResolve != null) {
1670 return null;
1671 } else {
1672 systemResolve = appList.get(i);
1673 }
1674 }
1675 } catch (PackageManager.NameNotFoundException e) {
1676 Log.w(TAG, "Unable to get info about resolve results", e);
1677 return null;
1678 }
1679 }
1680 return systemResolve;
1681 }
1682
1683 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1684 List<ResolveInfo> appList) {
1685 // If the list contains the above resolved activity, then it can't be
1686 // ResolverActivity itself.
1687 for (int i = 0; i < appList.size(); ++i) {
1688 ResolveInfo tmp = appList.get(i);
1689 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1690 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1691 return false;
1692 }
1693 }
1694 return true;
1695 }
1696
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001697 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1698 XmlResourceParser parser) {
1699 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1700 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1701 final String uri = getAttributeValue(parser, ATTR_URI);
1702
1703 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001704 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001705 try {
1706 ComponentName cn;
1707 try {
1708 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001709 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001710 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001711 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001712 new String[] { packageName });
1713 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001714 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001715 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001716 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001717 intent.setComponent(cn);
1718 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1719 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1720
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001721 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001722 intent);
1723 } catch (PackageManager.NameNotFoundException e) {
1724 Log.w(TAG, "Unable to add favorite: " + packageName +
1725 "/" + className, e);
1726 }
1727 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001728 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001729 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001730 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001731 } else {
1732 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1733 return -1;
1734 }
1735 }
1736
1737 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1738 Intent intent) {
1739 long id = generateNewItemId();
1740 values.put(Favorites.INTENT, intent.toUri(0));
1741 values.put(Favorites.TITLE, title);
1742 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1743 values.put(Favorites.SPANX, 1);
1744 values.put(Favorites.SPANY, 1);
1745 values.put(Favorites._ID, id);
1746 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1747 return -1;
1748 } else {
1749 return id;
1750 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001751 }
1752
1753 private long addFolder(SQLiteDatabase db, ContentValues values) {
1754 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1755 values.put(Favorites.SPANX, 1);
1756 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001757 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001758 values.put(Favorites._ID, id);
1759 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1760 return -1;
1761 } else {
1762 return id;
1763 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001764 }
1765
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001766 private ComponentName getSearchWidgetProvider() {
1767 SearchManager searchManager =
1768 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1769 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1770 if (searchComponent == null) return null;
1771 return getProviderInPackage(searchComponent.getPackageName());
1772 }
1773
1774 /**
1775 * Gets an appwidget provider from the given package. If the package contains more than
1776 * one appwidget provider, an arbitrary one is returned.
1777 */
1778 private ComponentName getProviderInPackage(String packageName) {
1779 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1780 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1781 if (providers == null) return null;
1782 final int providerCount = providers.size();
1783 for (int i = 0; i < providerCount; i++) {
1784 ComponentName provider = providers.get(i).provider;
1785 if (provider != null && provider.getPackageName().equals(packageName)) {
1786 return provider;
1787 }
1788 }
1789 return null;
1790 }
1791
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001792 private boolean addAppWidget(XmlResourceParser parser, int type,
1793 SQLiteDatabase db, ContentValues values)
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001794 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001795
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001796 String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1797 String className = getAttributeValue(parser, ATTR_CLASS_NAME);
Mike Cleronb87bd162009-10-30 16:36:56 -07001798
1799 if (packageName == null || className == null) {
1800 return false;
1801 }
Romain Guy693599f2010-03-23 10:58:18 -07001802
1803 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001804 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001805 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001806 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001807 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001808 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001809 new String[] { packageName });
1810 cn = new ComponentName(packages[0], className);
1811 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001812 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001813 } catch (Exception e1) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001814 System.out.println("Can't find widget provider: " + className);
Romain Guy693599f2010-03-23 10:58:18 -07001815 hasPackage = false;
1816 }
1817 }
1818
1819 if (hasPackage) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001820 String spanX = getAttributeValue(parser, ATTR_SPAN_X);
1821 String spanY = getAttributeValue(parser, ATTR_SPAN_Y);
1822
1823 values.put(Favorites.SPANX, spanX);
1824 values.put(Favorites.SPANY, spanY);
Winson Chungb3302ae2012-05-01 10:19:14 -07001825
1826 // Read the extras
1827 Bundle extras = new Bundle();
1828 int widgetDepth = parser.getDepth();
1829 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1830 parser.getDepth() > widgetDepth) {
1831 if (type != XmlPullParser.START_TAG) {
1832 continue;
1833 }
1834
Winson Chungb3302ae2012-05-01 10:19:14 -07001835 if (TAG_EXTRA.equals(parser.getName())) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001836 String key = getAttributeValue(parser, ATTR_KEY);
1837 String value = getAttributeValue(parser, ATTR_VALUE);
Winson Chungb3302ae2012-05-01 10:19:14 -07001838 if (key != null && value != null) {
1839 extras.putString(key, value);
1840 } else {
1841 throw new RuntimeException("Widget extras must have a key and value");
1842 }
1843 } else {
1844 throw new RuntimeException("Widgets can contain only extras");
1845 }
Winson Chungb3302ae2012-05-01 10:19:14 -07001846 }
1847
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001848 return addAppWidget(db, values, cn, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001849 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001850
Romain Guy693599f2010-03-23 10:58:18 -07001851 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001852 }
Adam Cohena043fa82014-07-23 14:49:38 -07001853
Bjorn Bringert7984c942009-12-09 15:38:25 +00001854 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001855 Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001856 boolean allocatedAppWidgets = false;
1857 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1858
1859 try {
1860 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001861
Mike Cleronb87bd162009-10-30 16:36:56 -07001862 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Mike Cleronb87bd162009-10-30 16:36:56 -07001863 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001864 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001865 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001866 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001867
1868 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001869
Michael Jurka8b805b12012-04-18 14:23:14 -07001870 // TODO: need to check return value
1871 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001872
1873 // Send a broadcast to configure the widget
1874 if (extras != null && !extras.isEmpty()) {
1875 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1876 intent.setComponent(cn);
1877 intent.putExtras(extras);
1878 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1879 mContext.sendBroadcast(intent);
1880 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001881 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001882 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001883 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001884
Mike Cleronb87bd162009-10-30 16:36:56 -07001885 return allocatedAppWidgets;
1886 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001887
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001888 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1889 XmlResourceParser parser) {
1890 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1891 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001892
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001893 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001894 String uri = null;
1895 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001896 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001897 intent = Intent.parseUri(uri, 0);
1898 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001899 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001900 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001901 }
1902
1903 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001904 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001905 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001906 }
1907
Adam Cohendcd297f2013-06-18 13:13:40 -07001908 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001909 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1910 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001911 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001912 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1913 values.put(Favorites.SPANX, 1);
1914 values.put(Favorites.SPANY, 1);
1915 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001916 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1917 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001918 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001919
Adam Cohen228da5a2011-07-27 22:23:47 -07001920 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1921 return -1;
1922 }
1923 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001924 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001925
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001926 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001927 final ContentResolver resolver = mContext.getContentResolver();
1928 Cursor c = null;
1929 int count = 0;
1930 int curScreen = 0;
1931
1932 try {
1933 c = resolver.query(uri, null, null, null, "title ASC");
1934 } catch (Exception e) {
1935 // Ignore
1936 }
1937
Dan Sandlerd5024042014-01-09 15:01:33 -05001938 // We already have a favorites database in the old provider
1939 if (c != null) {
1940 try {
1941 if (c.getCount() > 0) {
1942 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1943 final int intentIndex
1944 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1945 final int titleIndex
1946 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1947 final int iconTypeIndex
1948 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1949 final int iconIndex
1950 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1951 final int iconPackageIndex
1952 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1953 final int iconResourceIndex
1954 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1955 final int containerIndex
1956 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1957 final int itemTypeIndex
1958 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1959 final int screenIndex
1960 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1961 final int cellXIndex
1962 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1963 final int cellYIndex
1964 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1965 final int uriIndex
1966 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1967 final int displayModeIndex
1968 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001969 final int profileIndex
1970 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001971
1972 int i = 0;
1973 int curX = 0;
1974 int curY = 0;
1975
1976 final LauncherAppState app = LauncherAppState.getInstance();
1977 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1978 final int width = (int) grid.numColumns;
1979 final int height = (int) grid.numRows;
1980 final int hotseatWidth = (int) grid.numHotseatIcons;
1981
1982 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1983
Adam Cohen72960972014-01-15 18:13:55 -08001984 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1985 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001986 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001987
1988 while (c.moveToNext()) {
1989 final int itemType = c.getInt(itemTypeIndex);
1990 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1991 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1992 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1993 continue;
1994 }
1995
1996 final int cellX = c.getInt(cellXIndex);
1997 final int cellY = c.getInt(cellYIndex);
1998 final int screen = c.getInt(screenIndex);
1999 int container = c.getInt(containerIndex);
2000 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01002001
2002 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
2003 UserHandleCompat userHandle;
2004 final long userSerialNumber;
2005 if (profileIndex != -1 && !c.isNull(profileIndex)) {
2006 userSerialNumber = c.getInt(profileIndex);
2007 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
2008 } else {
2009 // Default to the serial number of this user, for older
2010 // shortcuts.
2011 userHandle = UserHandleCompat.myUserHandle();
2012 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
2013 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002014 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002015 + c.getString(titleIndex) + "\" ("
2016 + cellX + "," + cellY + "@"
2017 + LauncherSettings.Favorites.containerToString(container)
2018 + "/" + screen
2019 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05002020
2021 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08002022
2023 final Intent intent;
2024 final ComponentName cn;
2025 try {
2026 intent = Intent.parseUri(intentStr, 0);
2027 } catch (URISyntaxException e) {
2028 // bogus intent?
2029 Launcher.addDumpLog(TAG,
2030 "skipping invalid intent uri", true);
2031 continue;
2032 }
2033
2034 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05002035 if (TextUtils.isEmpty(intentStr)) {
2036 // no intent? no icon
2037 Launcher.addDumpLog(TAG, "skipping empty intent", true);
2038 continue;
Adam Cohen72960972014-01-15 18:13:55 -08002039 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01002040 !LauncherModel.isValidPackageActivity(mContext, cn,
2041 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08002042 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08002043 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08002044 "no longer exists.", true);
2045 continue;
Adam Cohen72960972014-01-15 18:13:55 -08002046 } else if (container ==
2047 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2048 // Dedupe icons directly on the workspace
2049
Adam Cohen556f6132014-01-15 15:18:08 -08002050 // Canonicalize
2051 // the Play Store sets the package parameter, but Launcher
2052 // does not, so we clear that out to keep them the same
2053 intent.setPackage(null);
2054 final String key = intent.toUri(0);
2055 if (seenIntents.contains(key)) {
2056 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05002057 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08002058 } else {
2059 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05002060 }
2061 }
2062 }
2063
2064 ContentValues values = new ContentValues(c.getColumnCount());
2065 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
2066 values.put(LauncherSettings.Favorites.INTENT, intentStr);
2067 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
2068 values.put(LauncherSettings.Favorites.ICON_TYPE,
2069 c.getInt(iconTypeIndex));
2070 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
2071 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
2072 c.getString(iconPackageIndex));
2073 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
2074 c.getString(iconResourceIndex));
2075 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
2076 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
2077 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
2078 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
2079 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01002080 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05002081
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002082 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2083 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05002084 }
2085
2086 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2087 // In a folder or in the hotseat, preserve position
2088 values.put(LauncherSettings.Favorites.SCREEN, screen);
2089 values.put(LauncherSettings.Favorites.CELLX, cellX);
2090 values.put(LauncherSettings.Favorites.CELLY, cellY);
2091 } else {
Adam Cohen72960972014-01-15 18:13:55 -08002092 // For items contained directly on one of the workspace screen,
2093 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05002094 }
2095
2096 values.put(LauncherSettings.Favorites.CONTAINER, container);
2097
Adam Cohen72960972014-01-15 18:13:55 -08002098 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
2099 shortcuts.add(values);
2100 } else {
2101 folders.add(values);
2102 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002103 }
2104
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002105 // Now that we have all the hotseat icons, let's go through them left-right
2106 // and assign valid locations for them in the new hotseat
2107 final int N = hotseat.size();
2108 for (int idx=0; idx<N; idx++) {
2109 int hotseatX = hotseat.keyAt(idx);
2110 ContentValues values = hotseat.valueAt(idx);
2111
2112 if (hotseatX == grid.hotseatAllAppsRank) {
2113 // let's drop this in the next available hole in the hotseat
2114 while (++hotseatX < hotseatWidth) {
2115 if (hotseat.get(hotseatX) == null) {
2116 // found a spot! move it here
2117 values.put(LauncherSettings.Favorites.SCREEN,
2118 hotseatX);
2119 break;
2120 }
2121 }
2122 }
2123 if (hotseatX >= hotseatWidth) {
2124 // no room for you in the hotseat? it's off to the desktop with you
2125 values.put(LauncherSettings.Favorites.CONTAINER,
2126 Favorites.CONTAINER_DESKTOP);
2127 }
2128 }
2129
Adam Cohen72960972014-01-15 18:13:55 -08002130 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2131 // Folders first
2132 allItems.addAll(folders);
2133 // Then shortcuts
2134 allItems.addAll(shortcuts);
2135
2136 // Layout all the folders
2137 for (ContentValues values: allItems) {
2138 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2139 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2140 // Hotseat items and folder items have already had their
2141 // location information set. Nothing to be done here.
2142 continue;
2143 }
2144 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2145 values.put(LauncherSettings.Favorites.CELLX, curX);
2146 values.put(LauncherSettings.Favorites.CELLY, curY);
2147 curX = (curX + 1) % width;
2148 if (curX == 0) {
2149 curY = (curY + 1);
2150 }
2151 // Leave the last row of icons blank on every screen
2152 if (curY == height - 1) {
2153 curScreen = (int) generateNewScreenId();
2154 curY = 0;
2155 }
2156 }
2157
2158 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002159 db.beginTransaction();
2160 try {
Adam Cohen72960972014-01-15 18:13:55 -08002161 for (ContentValues row: allItems) {
2162 if (row == null) continue;
2163 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002164 < 0) {
2165 return;
2166 } else {
2167 count++;
2168 }
2169 }
2170 db.setTransactionSuccessful();
2171 } finally {
2172 db.endTransaction();
2173 }
2174 }
2175
2176 db.beginTransaction();
2177 try {
2178 for (i=0; i<=curScreen; i++) {
2179 final ContentValues values = new ContentValues();
2180 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2181 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2182 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2183 < 0) {
2184 return;
2185 }
2186 }
2187 db.setTransactionSuccessful();
2188 } finally {
2189 db.endTransaction();
2190 }
2191 }
2192 } finally {
2193 c.close();
2194 }
2195 }
2196
2197 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2198 + (curScreen+1) + " screens", true);
2199
2200 // ensure that new screens are created to hold these icons
2201 setFlagJustLoadedOldDb();
2202
2203 // Update max IDs; very important since we just grabbed IDs from another database
2204 mMaxItemId = initializeMaxItemId(db);
2205 mMaxScreenId = initializeMaxScreenId(db);
2206 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2207 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002208 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002209
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002210 /**
2211 * Build a query string that will match any row where the column matches
2212 * anything in the values list.
2213 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002214 private static String buildOrWhereString(String column, int[] values) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002215 StringBuilder selectWhere = new StringBuilder();
2216 for (int i = values.length - 1; i >= 0; i--) {
2217 selectWhere.append(column).append("=").append(values[i]);
2218 if (i > 0) {
2219 selectWhere.append(" OR ");
2220 }
2221 }
2222 return selectWhere.toString();
2223 }
2224
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002225 /**
2226 * Return attribute value, attempting launcher-specific namespace first
2227 * before falling back to anonymous attribute.
2228 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002229 private static String getAttributeValue(XmlResourceParser parser, String attribute) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002230 String value = parser.getAttributeValue(
2231 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2232 if (value == null) {
2233 value = parser.getAttributeValue(null, attribute);
2234 }
2235 return value;
2236 }
2237
2238 /**
2239 * Return attribute resource value, attempting launcher-specific namespace
2240 * first before falling back to anonymous attribute.
2241 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002242 private static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002243 int defaultValue) {
2244 int value = parser.getAttributeResourceValue(
2245 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2246 defaultValue);
2247 if (value == defaultValue) {
2248 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2249 }
2250 return value;
2251 }
2252
2253 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2254 to.put(key, from.getAsInteger(key));
2255 }
2256
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002257 static class SqlArguments {
2258 public final String table;
2259 public final String where;
2260 public final String[] args;
2261
2262 SqlArguments(Uri url, String where, String[] args) {
2263 if (url.getPathSegments().size() == 1) {
2264 this.table = url.getPathSegments().get(0);
2265 this.where = where;
2266 this.args = args;
2267 } else if (url.getPathSegments().size() != 2) {
2268 throw new IllegalArgumentException("Invalid URI: " + url);
2269 } else if (!TextUtils.isEmpty(where)) {
2270 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2271 } else {
2272 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002273 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002274 this.args = null;
2275 }
2276 }
2277
2278 SqlArguments(Uri url) {
2279 if (url.getPathSegments().size() == 1) {
2280 table = url.getPathSegments().get(0);
2281 where = null;
2282 args = null;
2283 } else {
2284 throw new IllegalArgumentException("Invalid URI: " + url);
2285 }
2286 }
2287 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -07002288
2289 static interface WorkspaceLoader {
2290 /**
2291 * @param screenIds A mutable list of screen its
2292 * @return the number of workspace items added.
2293 */
2294 int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds);
2295 }
2296
2297 private static class SimpleWorkspaceLoader implements WorkspaceLoader {
2298 private final Resources mRes;
2299 private final int mWorkspaceId;
2300 private final DatabaseHelper mHelper;
2301
2302 SimpleWorkspaceLoader(DatabaseHelper helper, Resources res, int workspaceId) {
2303 mHelper = helper;
2304 mRes = res;
2305 mWorkspaceId = workspaceId;
2306 }
2307
2308 @Override
2309 public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
2310 return mHelper.loadFavoritesRecursive(db, mRes, mWorkspaceId, screenIds);
2311 }
2312 }
Adam Cohen72960972014-01-15 18:13:55 -08002313}