blob: 437c2ad9609fcd6a7698754d5a5692e51471ce7c [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;
Jeff Sharkey5aeef582014-04-14 13:26:42 -070036import android.content.pm.PackageInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.content.pm.PackageManager;
Jason Monk41314972014-03-03 16:11:30 -050038import android.content.pm.ResolveInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.database.Cursor;
43import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteOpenHelper;
46import android.database.sqlite.SQLiteQueryBuilder;
47import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080048import android.graphics.Bitmap;
49import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070051import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import android.provider.Settings;
53import android.text.TextUtils;
54import android.util.AttributeSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050056import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080057import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070058
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040061import com.android.launcher3.config.ProviderConfig;
Kenny Guyed131872014-04-30 03:02:21 +010062import com.android.launcher3.LauncherSettings.Favorites;
Michael Jurka8b805b12012-04-18 14:23:14 -070063
64import org.xmlpull.v1.XmlPullParser;
65import org.xmlpull.v1.XmlPullParserException;
66
Dan Sandlerd5024042014-01-09 15:01:33 -050067import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070069import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070070import java.util.ArrayList;
Dan Sandlerd5024042014-01-09 15:01:33 -050071import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000072import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080075 private static final String TAG = "Launcher.LauncherProvider";
76 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
78 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070079
Kenny Guyed131872014-04-30 03:02:21 +010080 private static final int DATABASE_VERSION = 20;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
Adam Cohene25af792013-06-06 23:08:25 -070082 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040083 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070084
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050085 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050086 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050087
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070089 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070091 static final String UPGRADED_FROM_OLD_DATABASE =
92 "UPGRADED_FROM_OLD_DATABASE";
93 static final String EMPTY_DATABASE_CREATED =
94 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020095 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
96 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
Winson Chungb3302ae2012-05-01 10:19:14 -070098 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070099 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -0700100
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 private LauncherProviderChangeListener mListener;
102
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700103 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700104 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700105 * {@link AppWidgetHost#deleteHost()} is called during database creation.
106 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
107 */
108 static final Uri CONTENT_APPWIDGET_RESET_URI =
109 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700110
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700111 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700112 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
114 @Override
115 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400116 final Context context = getContext();
117 mOpenHelper = new DatabaseHelper(context);
118 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119 return true;
120 }
121
Winson Chung0b560dd2014-01-21 13:00:26 -0800122 public boolean wasNewDbCreated() {
123 return mOpenHelper.wasNewDbCreated();
124 }
125
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700126 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
127 mListener = listener;
128 }
129
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800130 @Override
131 public String getType(Uri uri) {
132 SqlArguments args = new SqlArguments(uri, null, null);
133 if (TextUtils.isEmpty(args.where)) {
134 return "vnd.android.cursor.dir/" + args.table;
135 } else {
136 return "vnd.android.cursor.item/" + args.table;
137 }
138 }
139
140 @Override
141 public Cursor query(Uri uri, String[] projection, String selection,
142 String[] selectionArgs, String sortOrder) {
143
144 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
145 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
146 qb.setTables(args.table);
147
Romain Guy73b979d2009-06-09 12:57:21 -0700148 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
150 result.setNotificationUri(getContext().getContentResolver(), uri);
151
152 return result;
153 }
154
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 private static long dbInsertAndCheck(DatabaseHelper helper,
156 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500157 if (values == null) {
158 throw new RuntimeException("Error: attempting to insert null values");
159 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500160 if (!values.containsKey(LauncherSettings.BaseLauncherColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 throw new RuntimeException("Error: attempting to add item without specifying an id");
162 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500163 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 return db.insert(table, nullColumnHack, values);
165 }
166
Adam Cohen228da5a2011-07-27 22:23:47 -0700167 private static void deleteId(SQLiteDatabase db, long id) {
168 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
169 SqlArguments args = new SqlArguments(uri, null, null);
170 db.delete(args.table, args.where, args.args);
171 }
172
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173 @Override
174 public Uri insert(Uri uri, ContentValues initialValues) {
175 SqlArguments args = new SqlArguments(uri);
176
177 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400178 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700179 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 if (rowId <= 0) return null;
181
182 uri = ContentUris.withAppendedId(uri, rowId);
183 sendNotify(uri);
184
185 return uri;
186 }
187
188 @Override
189 public int bulkInsert(Uri uri, ContentValues[] values) {
190 SqlArguments args = new SqlArguments(uri);
191
192 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
193 db.beginTransaction();
194 try {
195 int numValues = values.length;
196 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400197 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700198 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
199 return 0;
200 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 }
202 db.setTransactionSuccessful();
203 } finally {
204 db.endTransaction();
205 }
206
207 sendNotify(uri);
208 return values.length;
209 }
210
211 @Override
Yura085c8532014-02-11 15:15:29 +0000212 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
213 throws OperationApplicationException {
214 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
215 db.beginTransaction();
216 try {
217 ContentProviderResult[] result = super.applyBatch(operations);
218 db.setTransactionSuccessful();
219 return result;
220 } finally {
221 db.endTransaction();
222 }
223 }
224
225 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800226 public int delete(Uri uri, String selection, String[] selectionArgs) {
227 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
228
229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
230 int count = db.delete(args.table, args.where, args.args);
231 if (count > 0) sendNotify(uri);
232
233 return count;
234 }
235
236 @Override
237 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
238 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
239
Chris Wren1ada10d2013-09-13 18:01:38 -0400240 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
242 int count = db.update(args.table, values, args.where, args.args);
243 if (count > 0) sendNotify(uri);
244
245 return count;
246 }
247
248 private void sendNotify(Uri uri) {
249 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
250 if (notify == null || "true".equals(notify)) {
251 getContext().getContentResolver().notifyChange(uri, null);
252 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400253
254 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400255 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700256 if (mListener != null) {
257 mListener.onLauncherProviderChange();
258 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400259 }
260
261 private void addModifiedTime(ContentValues values) {
262 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800263 }
264
Adam Cohendcd297f2013-06-18 13:13:40 -0700265 public long generateNewItemId() {
266 return mOpenHelper.generateNewItemId();
267 }
268
Winson Chungc763c4e2013-07-19 13:49:06 -0700269 public void updateMaxItemId(long id) {
270 mOpenHelper.updateMaxItemId(id);
271 }
272
Adam Cohendcd297f2013-06-18 13:13:40 -0700273 public long generateNewScreenId() {
274 return mOpenHelper.generateNewScreenId();
275 }
276
277 // This is only required one time while loading the workspace during the
278 // upgrade path, and should never be called from anywhere else.
279 public void updateMaxScreenId(long maxScreenId) {
280 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700281 }
282
Brian Muramatsu5524b492012-10-02 16:55:54 -0700283 /**
Adam Cohene25af792013-06-06 23:08:25 -0700284 * @param Should we load the old db for upgrade? first run only.
285 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700286 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400287 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700288 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
289
Winson Chungc763c4e2013-07-19 13:49:06 -0700290 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700291
Winson Chungc763c4e2013-07-19 13:49:06 -0700292 sJustLoadedFromOldDb = false;
293 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700294
295 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700296 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700297 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700298 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700299 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700300 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700301 }
302
303 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700304 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
305 */
Michael Jurka45355c42012-10-08 13:21:35 +0200306 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400307 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700308 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700309
Winson Chungc763c4e2013-07-19 13:49:06 -0700310 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500311 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200312 int workspaceResId = origWorkspaceResId;
313
Brian Muramatsu5524b492012-10-02 16:55:54 -0700314 // Use default workspace resource if none provided
315 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800316 workspaceResId =
317 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700318 }
319
Michael Jurkab85f8a42012-04-25 15:48:32 -0700320 // Populate favorites table with initial favorites
321 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700322 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200323 if (origWorkspaceResId != 0) {
324 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
325 }
Adam Cohene25af792013-06-06 23:08:25 -0700326
Brian Muramatsu5524b492012-10-02 16:55:54 -0700327 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700328 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700329 editor.commit();
330 }
331 }
332
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 public void migrateLauncher2Shortcuts() {
334 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400335 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 }
337
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800338 private static int getDefaultWorkspaceResourceId() {
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800339 if (LauncherAppState.isDisableAllApps()) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800340 return R.xml.default_workspace_no_all_apps;
341 } else {
342 return R.xml.default_workspace;
343 }
344 }
345
Winson Chungc763c4e2013-07-19 13:49:06 -0700346 private static interface ContentValuesCallback {
347 public void onRow(ContentValues values);
348 }
349
Adam Cohen6dbe0492013-12-02 17:00:14 -0800350 private static boolean shouldImportLauncher2Database(Context context) {
351 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
352
353 // We don't import the old databse for tablets, as the grid size has changed.
354 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
355 }
356
Dan Sandlerd5024042014-01-09 15:01:33 -0500357 public void deleteDatabase() {
358 // Are you sure? (y/n)
359 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500360 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500361 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500362 if (dbFile.exists()) {
363 SQLiteDatabase.deleteDatabase(dbFile);
364 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500365 mOpenHelper = new DatabaseHelper(getContext());
366 }
367
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500369 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800370 private static final String TAG_FAVORITES = "favorites";
371 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700372 private static final String TAG_CLOCK = "clock";
373 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700374 private static final String TAG_APPWIDGET = "appwidget";
375 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700376 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700377 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700378 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400379 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700380
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700381 private static final String ATTR_TITLE = "title";
382 private static final String ATTR_ICON = "icon";
383 private static final String ATTR_URI = "uri";
384 private static final String ATTR_PACKAGE_NAME = "packageName";
385 private static final String ATTR_CLASS_NAME = "className";
386
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800387 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700388 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700389 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700390 private long mMaxItemId = -1;
391 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800392
Winson Chung0b560dd2014-01-21 13:00:26 -0800393 private boolean mNewDbCreated = false;
394
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 DatabaseHelper(Context context) {
396 super(context, DATABASE_NAME, null, DATABASE_VERSION);
397 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700398 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700399 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700400
401 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
402 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700403 if (mMaxItemId == -1) {
404 mMaxItemId = initializeMaxItemId(getWritableDatabase());
405 }
406 if (mMaxScreenId == -1) {
407 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700408 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800409 }
410
Winson Chung0b560dd2014-01-21 13:00:26 -0800411 public boolean wasNewDbCreated() {
412 return mNewDbCreated;
413 }
414
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700415 /**
416 * Send notification that we've deleted the {@link AppWidgetHost},
417 * probably as part of the initial database creation. The receiver may
418 * want to re-call {@link AppWidgetHost#startListening()} to ensure
419 * callbacks are correctly set.
420 */
421 private void sendAppWidgetResetNotify() {
422 final ContentResolver resolver = mContext.getContentResolver();
423 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
424 }
425
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800426 @Override
427 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800428 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700429
Adam Cohendcd297f2013-06-18 13:13:40 -0700430 mMaxItemId = 1;
431 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800432 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700433
Kenny Guyed131872014-04-30 03:02:21 +0100434 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
435 long userSerialNumber = userManager.getSerialNumberForUser(
436 UserHandleCompat.myUserHandle());
437
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438 db.execSQL("CREATE TABLE favorites (" +
439 "_id INTEGER PRIMARY KEY," +
440 "title TEXT," +
441 "intent TEXT," +
442 "container INTEGER," +
443 "screen INTEGER," +
444 "cellX INTEGER," +
445 "cellY INTEGER," +
446 "spanX INTEGER," +
447 "spanY INTEGER," +
448 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700449 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800450 "isShortcut INTEGER," +
451 "iconType INTEGER," +
452 "iconPackage TEXT," +
453 "iconResource TEXT," +
454 "icon BLOB," +
455 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400456 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400457 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500458 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100459 "restored INTEGER NOT NULL DEFAULT 0," +
460 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800461 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700462 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700464 // Database was just created, so wipe any previous widgets
465 if (mAppWidgetHost != null) {
466 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700467 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700469
Adam Cohen6dbe0492013-12-02 17:00:14 -0800470 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500471 // Try converting the old database
472 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
473 public void onRow(ContentValues values) {
474 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
475 if (container == Favorites.CONTAINER_DESKTOP) {
476 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
477 screen = (int) upgradeLauncherDb_permuteScreens(screen);
478 values.put(LauncherSettings.Favorites.SCREEN, screen);
479 }
480 }
481 };
482 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
483 "/old_favorites?notify=true");
484 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
485 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400486 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500487 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
488 // If we fail, then set a flag to load the default workspace
489 setFlagEmptyDbCreated();
490 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700491 }
492 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500493 // Right now, in non-default workspace cases, we want to run the final
494 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
495 // set that flag too.
496 setFlagJustLoadedOldDb();
497 } else {
498 // Fresh and clean launcher DB.
499 mMaxItemId = initializeMaxItemId(db);
500 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800501 }
502 }
503
Adam Cohendcd297f2013-06-18 13:13:40 -0700504 private void addWorkspacesTable(SQLiteDatabase db) {
505 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
506 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400507 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
508 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700509 ");");
510 }
511
Adam Cohen119285e2014-04-02 16:59:08 -0700512 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700513 // Delete items directly on the workspace who's screen id doesn't exist
514 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
515 // AND container = -100"
516 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
517 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700518 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700519 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
520 " AND " +
521 LauncherSettings.Favorites.CONTAINER + " = " +
522 LauncherSettings.Favorites.CONTAINER_DESKTOP;
523 db.execSQL(removeOrphanedDesktopItems);
524
525 // Delete items contained in folders which no longer exist (after above statement)
526 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
527 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
528 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
529 " WHERE " +
530 LauncherSettings.Favorites.CONTAINER + " <> " +
531 LauncherSettings.Favorites.CONTAINER_DESKTOP +
532 " AND "
533 + LauncherSettings.Favorites.CONTAINER + " <> " +
534 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
535 " AND "
536 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
537 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
538 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
539 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
540 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700541 }
542
Winson Chungc763c4e2013-07-19 13:49:06 -0700543 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400544 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700545 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
546 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700547 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
548 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700549 editor.commit();
550 }
551
Winson Chungc763c4e2013-07-19 13:49:06 -0700552 private void setFlagEmptyDbCreated() {
553 String spKey = LauncherAppState.getSharedPreferencesKey();
554 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
555 SharedPreferences.Editor editor = sp.edit();
556 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
557 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
558 editor.commit();
559 }
560
561 // We rearrange the screens from the old launcher
562 // 12345 -> 34512
563 private long upgradeLauncherDb_permuteScreens(long screen) {
564 if (screen >= 2) {
565 return screen - 2;
566 } else {
567 return screen + 3;
568 }
569 }
570
571 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
572 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800573 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 boolean converted = false;
575
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 final ContentResolver resolver = mContext.getContentResolver();
577 Cursor cursor = null;
578
579 try {
580 cursor = resolver.query(uri, null, null, null, null);
581 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700582 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800583 }
584
585 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700586 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700588 if (cursor.getCount() > 0) {
589 converted = copyFromCursor(db, cursor, cb) > 0;
590 if (converted && deleteRows) {
591 resolver.delete(uri, null, null);
592 }
593 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800594 } finally {
595 cursor.close();
596 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700598
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700600 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800601 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700603
604 // Update max item id
605 mMaxItemId = initializeMaxItemId(db);
606 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
609 return converted;
610 }
611
Winson Chungc763c4e2013-07-19 13:49:06 -0700612 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700613 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
615 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
616 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
617 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
618 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
619 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
620 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
621 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
622 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
623 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
624 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
625 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
626 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
627
628 ContentValues[] rows = new ContentValues[c.getCount()];
629 int i = 0;
630 while (c.moveToNext()) {
631 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700632 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
634 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
635 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
636 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
637 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
638 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
639 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
640 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700641 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800642 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
643 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
644 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
645 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
646 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700647 if (cb != null) {
648 cb.onRow(values);
649 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 rows[i++] = values;
651 }
652
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700654 if (i > 0) {
655 db.beginTransaction();
656 try {
657 int numValues = rows.length;
658 for (i = 0; i < numValues; i++) {
659 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
660 return 0;
661 } else {
662 total++;
663 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700665 db.setTransactionSuccessful();
666 } finally {
667 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800669 }
670
671 return total;
672 }
673
674 @Override
675 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700676 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700677
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700679 if (version < 3) {
680 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 db.beginTransaction();
682 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700683 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700685 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700687 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688 } catch (SQLException ex) {
689 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800690 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 } finally {
692 db.endTransaction();
693 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700694
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800695 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700696 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 convertWidgets(db);
698 }
699 }
Romain Guy73b979d2009-06-09 12:57:21 -0700700
701 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800702 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700703 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700704
Romain Guy509cd6a2010-03-23 15:10:56 -0700705 // Where's version 5?
706 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400707 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700708 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
709 // but version 5 on there was the updateContactsShortcuts change
710 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
711 // The updateContactsShortcuts change is idempotent, so running it twice
712 // is okay so we'll do that when upgrading the devices that shipped with it.
713 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800714 // We went from 3 to 5 screens. Move everything 1 to the right
715 db.beginTransaction();
716 try {
717 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
718 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -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);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800722 } finally {
723 db.endTransaction();
724 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700725
Romain Guy509cd6a2010-03-23 15:10:56 -0700726 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800727 if (updateContactsShortcuts(db)) {
728 version = 6;
729 }
730 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000731
732 if (version < 7) {
733 // Version 7 gets rid of the special search widget.
734 convertWidgets(db);
735 version = 7;
736 }
737
Joe Onorato0589f0f2010-02-08 13:44:00 -0800738 if (version < 8) {
739 // Version 8 (froyo) has the icons all normalized. This should
740 // already be the case in practice, but we now rely on it and don't
741 // resample the images each time.
742 normalizeIcons(db);
743 version = 8;
744 }
745
Winson Chung3d503fb2011-07-13 17:25:49 -0700746 if (version < 9) {
747 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
748 // 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 -0700749 if (mMaxItemId == -1) {
750 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700751 }
752
753 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800754 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700755 version = 9;
756 }
757
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700758 // We bumped the version three time during JB, once to update the launch flags, once to
759 // update the override for the default launch animation and once to set the mimetype
760 // to improve startup performance
761 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700762 // Contact shortcuts need a different set of flags to be launched now
763 // The updateContactsShortcuts change is idempotent, so we can keep using it like
764 // back in the Donut days
765 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700766 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700767 }
768
Adam Cohendcd297f2013-06-18 13:13:40 -0700769 if (version < 13) {
770 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
771 // to persist workspace screens and their relative order.
772 mMaxScreenId = 0;
773
774 // This will never happen in the wild, but when we switch to using workspace
775 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700776 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700777
778 addWorkspacesTable(db);
779 version = 13;
780 }
781
Chris Wrend5e66bf2013-09-16 14:02:29 -0400782 if (version < 14) {
783 db.beginTransaction();
784 try {
785 // Insert new column for holding widget provider name
786 db.execSQL("ALTER TABLE favorites " +
787 "ADD COLUMN appWidgetProvider TEXT;");
788 db.setTransactionSuccessful();
789 version = 14;
790 } catch (SQLException ex) {
791 // Old version remains, which means we wipe old data
792 Log.e(TAG, ex.getMessage(), ex);
793 } finally {
794 db.endTransaction();
795 }
796 }
797
Chris Wren1ada10d2013-09-13 18:01:38 -0400798 if (version < 15) {
799 db.beginTransaction();
800 try {
801 // Insert new column for holding update timestamp
802 db.execSQL("ALTER TABLE favorites " +
803 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
804 db.execSQL("ALTER TABLE workspaceScreens " +
805 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
806 db.setTransactionSuccessful();
807 version = 15;
808 } catch (SQLException ex) {
809 // Old version remains, which means we wipe old data
810 Log.e(TAG, ex.getMessage(), ex);
811 } finally {
812 db.endTransaction();
813 }
814 }
815
Chris Wrenf4d08112014-01-16 18:13:56 -0500816
817 if (version < 16) {
818 db.beginTransaction();
819 try {
820 // Insert new column for holding restore status
821 db.execSQL("ALTER TABLE favorites " +
822 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
823 db.setTransactionSuccessful();
824 version = 16;
825 } catch (SQLException ex) {
826 // Old version remains, which means we wipe old data
827 Log.e(TAG, ex.getMessage(), ex);
828 } finally {
829 db.endTransaction();
830 }
831 }
832
Adam Cohen71e03b92014-02-21 14:09:53 -0800833 if (version < 17) {
834 // We use the db version upgrade here to identify users who may not have seen
835 // clings yet (because they weren't available), but for whom the clings are now
836 // available (tablet users). Because one of the possible cling flows (migration)
837 // is very destructive (wipes out workspaces), we want to prevent this from showing
838 // until clear data. We do so by marking that the clings have been shown.
839 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
840 version = 17;
841 }
842
Adam Cohen119285e2014-04-02 16:59:08 -0700843 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700844 // No-op
845 version = 18;
846 }
847
848 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700849 // Due to a data loss bug, some users may have items associated with screen ids
850 // which no longer exist. Since this can cause other problems, and since the user
851 // will never see these items anyway, we use database upgrade as an opportunity to
852 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700853 removeOrphanedItems(db);
854 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700855 }
856
Kenny Guyed131872014-04-30 03:02:21 +0100857 if (version < 20) {
858 // Add userId column
859 if (addProfileColumn(db)) {
860 version = 20;
861 }
862 // else old version remains, which means we wipe old data
863 }
864
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800865 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800866 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700868 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
869
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800870 onCreate(db);
871 }
872 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800873
Kenny Guyed131872014-04-30 03:02:21 +0100874 private boolean addProfileColumn(SQLiteDatabase db) {
875 db.beginTransaction();
876 try {
877 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
878 // Default to the serial number of this user, for older
879 // shortcuts.
880 long userSerialNumber = userManager.getSerialNumberForUser(
881 UserHandleCompat.myUserHandle());
882 // Insert new column for holding user serial number
883 db.execSQL("ALTER TABLE favorites " +
884 "ADD COLUMN profileId INTEGER DEFAULT "
885 + userSerialNumber + ";");
886 db.setTransactionSuccessful();
887 } catch (SQLException ex) {
888 // Old version remains, which means we wipe old data
889 Log.e(TAG, ex.getMessage(), ex);
890 return false;
891 } finally {
892 db.endTransaction();
893 }
894 return true;
895 }
896
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800897 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800898 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
899 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
900
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700901 Cursor c = null;
902 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800903 db.beginTransaction();
904 try {
905 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700906 c = db.query(TABLE_FAVORITES,
907 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800908 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700909 if (c == null) return false;
910
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800911 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700912
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800913 final int idIndex = c.getColumnIndex(Favorites._ID);
914 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700915
916 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800917 long favoriteId = c.getLong(idIndex);
918 final String intentUri = c.getString(intentIndex);
919 if (intentUri != null) {
920 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700921 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800922 android.util.Log.d("Home", intent.toString());
923 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700924 if (uri != null) {
925 final String data = uri.toString();
926 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
927 actionQuickContact.equals(intent.getAction())) &&
928 (data.startsWith("content://contacts/people/") ||
929 data.startsWith("content://com.android.contacts/" +
930 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800931
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700932 final Intent newIntent = new Intent(actionQuickContact);
933 // When starting from the launcher, start in a new, cleared task
934 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
935 // clear the whole thing preemptively here since
936 // QuickContactActivity will finish itself when launching other
937 // detail activities.
938 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
939 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700940 newIntent.putExtra(
941 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700942 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700943 // Determine the type and also put that in the shortcut
944 // (that can speed up launch a bit)
945 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800946
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700947 final ContentValues values = new ContentValues();
948 values.put(LauncherSettings.Favorites.INTENT,
949 newIntent.toUri(0));
950
951 String updateWhere = Favorites._ID + "=" + favoriteId;
952 db.update(TABLE_FAVORITES, values, updateWhere, null);
953 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800954 }
955 } catch (RuntimeException ex) {
956 Log.e(TAG, "Problem upgrading shortcut", ex);
957 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700958 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800959 }
960 }
961 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700962
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800963 db.setTransactionSuccessful();
964 } catch (SQLException ex) {
965 Log.w(TAG, "Problem while upgrading contacts", ex);
966 return false;
967 } finally {
968 db.endTransaction();
969 if (c != null) {
970 c.close();
971 }
972 }
973
974 return true;
975 }
976
Joe Onorato0589f0f2010-02-08 13:44:00 -0800977 private void normalizeIcons(SQLiteDatabase db) {
978 Log.d(TAG, "normalizing icons");
979
Joe Onorato346e1292010-02-18 10:34:24 -0500980 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800981 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400982 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800983 try {
984 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400985 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600986 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800987
988 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
989 Favorites.ICON_TYPE_BITMAP, null);
990
991 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
992 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
993
994 while (c.moveToNext()) {
995 long id = c.getLong(idIndex);
996 byte[] data = c.getBlob(iconIndex);
997 try {
998 Bitmap bitmap = Utilities.resampleIconBitmap(
999 BitmapFactory.decodeByteArray(data, 0, data.length),
1000 mContext);
1001 if (bitmap != null) {
1002 update.bindLong(1, id);
1003 data = ItemInfo.flattenBitmap(bitmap);
1004 if (data != null) {
1005 update.bindBlob(2, data);
1006 update.execute();
1007 }
1008 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001009 }
1010 } catch (Exception e) {
1011 if (!logged) {
1012 Log.e(TAG, "Failed normalizing icon " + id, e);
1013 } else {
1014 Log.e(TAG, "Also failed normalizing icon " + id);
1015 }
1016 logged = true;
1017 }
1018 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001019 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001020 } catch (SQLException ex) {
1021 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1022 } finally {
1023 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001024 if (update != null) {
1025 update.close();
1026 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001027 if (c != null) {
1028 c.close();
1029 }
1030 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001031 }
1032
1033 // Generates a new ID to use for an object in your database. This method should be only
1034 // called from the main UI thread. As an exception, we do call it when we call the
1035 // constructor from the worker thread; however, this doesn't extend until after the
1036 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1037 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 public long generateNewItemId() {
1039 if (mMaxItemId < 0) {
1040 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001041 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001042 mMaxItemId += 1;
1043 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 }
1045
Winson Chungc763c4e2013-07-19 13:49:06 -07001046 public void updateMaxItemId(long id) {
1047 mMaxItemId = id + 1;
1048 }
1049
Chris Wren5dee7af2013-12-20 17:22:11 -05001050 public void checkId(String table, ContentValues values) {
1051 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1052 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1053 mMaxScreenId = Math.max(id, mMaxScreenId);
1054 } else {
1055 mMaxItemId = Math.max(id, mMaxItemId);
1056 }
1057 }
1058
Adam Cohendcd297f2013-06-18 13:13:40 -07001059 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001060 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1061
1062 // get the result
1063 final int maxIdIndex = 0;
1064 long id = -1;
1065 if (c != null && c.moveToNext()) {
1066 id = c.getLong(maxIdIndex);
1067 }
Michael Jurka5130e402011-10-13 04:55:35 -07001068 if (c != null) {
1069 c.close();
1070 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001071
1072 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001073 throw new RuntimeException("Error: could not query max item id");
1074 }
1075
1076 return id;
1077 }
1078
1079 // Generates a new ID to use for an workspace screen in your database. This method
1080 // should be only called from the main UI thread. As an exception, we do call it when we
1081 // call the constructor from the worker thread; however, this doesn't extend until after the
1082 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1083 // after that point
1084 public long generateNewScreenId() {
1085 if (mMaxScreenId < 0) {
1086 throw new RuntimeException("Error: max screen id was not initialized");
1087 }
1088 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001089 // Log to disk
1090 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001091 return mMaxScreenId;
1092 }
1093
1094 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001095 // Log to disk
1096 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001097 mMaxScreenId = maxScreenId;
1098 }
1099
1100 private long initializeMaxScreenId(SQLiteDatabase db) {
1101 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1102
1103 // get the result
1104 final int maxIdIndex = 0;
1105 long id = -1;
1106 if (c != null && c.moveToNext()) {
1107 id = c.getLong(maxIdIndex);
1108 }
1109 if (c != null) {
1110 c.close();
1111 }
1112
1113 if (id == -1) {
1114 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001115 }
1116
Winson Chunga90303b2013-11-15 13:05:06 -08001117 // Log to disk
1118 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001119 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001120 }
1121
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001122 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001123 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001124 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001125 */
1126 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001127 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001128 final int[] bindSources = new int[] {
1129 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1130 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001131 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001132 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001133
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001135
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 db.beginTransaction();
1139 try {
1140 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001141 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001142 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001143
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001144 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001145
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001146 final ContentValues values = new ContentValues();
1147 while (c != null && c.moveToNext()) {
1148 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001149 int favoriteType = c.getInt(1);
1150
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001151 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001152 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001153 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001154
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001155 if (LOGD) {
1156 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1157 + " for favoriteId=" + favoriteId);
1158 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001159 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001160 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1161 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1162
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001163 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001164 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1165 values.put(LauncherSettings.Favorites.SPANX, 4);
1166 values.put(LauncherSettings.Favorites.SPANY, 1);
1167 } else {
1168 values.put(LauncherSettings.Favorites.SPANX, 2);
1169 values.put(LauncherSettings.Favorites.SPANY, 2);
1170 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171
1172 String updateWhere = Favorites._ID + "=" + favoriteId;
1173 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001174
Bjorn Bringert34251342009-12-15 13:33:11 +00001175 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001176 // TODO: check return value
1177 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001178 new ComponentName("com.android.alarmclock",
1179 "com.android.alarmclock.AnalogAppWidgetProvider"));
1180 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001181 // TODO: check return value
1182 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001183 new ComponentName("com.android.camera",
1184 "com.android.camera.PhotoAppWidgetProvider"));
1185 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001186 // TODO: check return value
1187 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001188 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001189 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001190 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001191 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001192 }
1193 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001194
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001195 db.setTransactionSuccessful();
1196 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001197 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001198 } finally {
1199 db.endTransaction();
1200 if (c != null) {
1201 c.close();
1202 }
1203 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001204
1205 // Update max item id
1206 mMaxItemId = initializeMaxItemId(db);
1207 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 }
1209
Michael Jurka8b805b12012-04-18 14:23:14 -07001210 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1211 throws XmlPullParserException, IOException {
1212 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001213 while ((type = parser.next()) != XmlPullParser.START_TAG
1214 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001215 ;
1216 }
1217
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001218 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001219 throw new XmlPullParserException("No start tag found");
1220 }
1221
1222 if (!parser.getName().equals(firstElementName)) {
1223 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1224 ", expected " + firstElementName);
1225 }
1226 }
1227
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001228 private static Intent buildMainIntent() {
1229 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1230 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1231 return intent;
1232 }
1233
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001234 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001235 * Loads the default set of favorite packages from an xml file.
1236 *
1237 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001238 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001239 */
Winson Chung6d092682011-11-16 18:43:26 -08001240 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001241 ContentValues values = new ContentValues();
1242
Daniel Sandler57dac262013-10-03 13:28:36 -04001243 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1244
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001245 int i = 0;
1246 try {
Winson Chung6d092682011-11-16 18:43:26 -08001247 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001248 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001249 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001250
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001251 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001252
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001253 int type;
1254 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1255 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1256
1257 if (type != XmlPullParser.START_TAG) {
1258 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001259 }
1260
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001261 boolean added = false;
1262 final String name = parser.getName();
1263
Daniel Sandler57dac262013-10-03 13:28:36 -04001264 if (TAG_INCLUDE.equals(name)) {
1265 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1266
1267 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1268
1269 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1270 "", resId));
1271
1272 if (resId != 0 && resId != workspaceResourceId) {
1273 // recursively load some more favorites, why not?
1274 i += loadFavorites(db, resId);
1275 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001276 } else {
1277 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1278 }
1279
1280 a.recycle();
1281
1282 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1283 continue;
1284 }
1285
1286 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001287 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1288
Winson Chung3d503fb2011-07-13 17:25:49 -07001289 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1290 if (a.hasValue(R.styleable.Favorite_container)) {
1291 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1292 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001293
Winson Chung6d092682011-11-16 18:43:26 -08001294 String screen = a.getString(R.styleable.Favorite_screen);
1295 String x = a.getString(R.styleable.Favorite_x);
1296 String y = a.getString(R.styleable.Favorite_y);
1297
Winson Chung6d092682011-11-16 18:43:26 -08001298 values.clear();
1299 values.put(LauncherSettings.Favorites.CONTAINER, container);
1300 values.put(LauncherSettings.Favorites.SCREEN, screen);
1301 values.put(LauncherSettings.Favorites.CELLX, x);
1302 values.put(LauncherSettings.Favorites.CELLY, y);
1303
Daniel Sandler57dac262013-10-03 13:28:36 -04001304 if (LOGD) {
1305 final String title = a.getString(R.styleable.Favorite_title);
1306 final String pkg = a.getString(R.styleable.Favorite_packageName);
1307 final String something = title != null ? title : pkg;
1308 Log.v(TAG, String.format(
1309 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1310 "", name,
1311 (something == null ? "" : (" \"" + something + "\"")),
1312 container, screen, x, y));
1313 }
1314
Winson Chung6d092682011-11-16 18:43:26 -08001315 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001316 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001317 added = id >= 0;
1318 } else if (TAG_SEARCH.equals(name)) {
1319 added = addSearchWidget(db, values);
1320 } else if (TAG_CLOCK.equals(name)) {
1321 added = addClockWidget(db, values);
1322 } else if (TAG_APPWIDGET.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001323 added = addAppWidget(parser, attrs, type, db, values, a);
Winson Chung6d092682011-11-16 18:43:26 -08001324 } else if (TAG_SHORTCUT.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001325 long id = addUriShortcut(db, values, mContext.getResources(), parser);
Winson Chung6d092682011-11-16 18:43:26 -08001326 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001327 } else if (TAG_RESOLVE.equals(name)) {
1328 // This looks through the contained favorites (or meta-favorites) and
1329 // attempts to add them as shortcuts in the fallback group's location
1330 // until one is added successfully.
1331 added = false;
1332 final int groupDepth = parser.getDepth();
1333 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1334 parser.getDepth() > groupDepth) {
1335 if (type != XmlPullParser.START_TAG) {
1336 continue;
1337 }
1338 final String fallback_item_name = parser.getName();
1339 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1340 R.styleable.Favorite);
1341 if (!added) {
1342 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001343 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001344 added = id >= 0;
1345 } else {
1346 Log.e(TAG, "Fallback groups can contain only favorites "
1347 + ar.toString());
1348 }
1349 }
1350 ar.recycle();
1351 }
Winson Chung6d092682011-11-16 18:43:26 -08001352 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001353 // Folder contents are nested in this XML file
1354 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001355
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001356 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1357 // Folder contents come from an external XML resource
1358 final Partner partner = Partner.get(mPackageManager);
1359 if (partner != null) {
1360 final Resources partnerRes = partner.getResources();
1361 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1362 "xml", partner.getPackageName());
1363 if (resId != 0) {
1364 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1365 beginDocument(partnerParser, TAG_FOLDER);
1366 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001367 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001368 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001369 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001370 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001371 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001372 }
1373 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001374 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001375 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001376 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001377 } catch (RuntimeException e) {
1378 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001379 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001380
Winson Chungc763c4e2013-07-19 13:49:06 -07001381 // Update the max item id after we have loaded the database
1382 if (mMaxItemId == -1) {
1383 mMaxItemId = initializeMaxItemId(db);
1384 }
1385
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001386 return i;
1387 }
1388
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001389 /**
1390 * Parse folder starting at current {@link XmlPullParser} location.
1391 */
1392 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1393 XmlResourceParser parser) throws IOException, XmlPullParserException {
1394 final String title;
1395 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1396 if (titleResId != 0) {
1397 title = res.getString(titleResId);
1398 } else {
1399 title = mContext.getResources().getString(R.string.folder_name);
1400 }
1401
1402 values.put(LauncherSettings.Favorites.TITLE, title);
1403 long folderId = addFolder(db, values);
1404 boolean added = folderId >= 0;
1405
1406 ArrayList<Long> folderItems = new ArrayList<Long>();
1407
1408 int type;
1409 int folderDepth = parser.getDepth();
1410 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1411 parser.getDepth() > folderDepth) {
1412 if (type != XmlPullParser.START_TAG) {
1413 continue;
1414 }
1415 final String tag = parser.getName();
1416
1417 final ContentValues childValues = new ContentValues();
1418 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1419
1420 if (LOGD) {
1421 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1422 final String uri = getAttributeValue(parser, ATTR_URI);
1423 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1424 tag, uri != null ? uri : pkg));
1425 }
1426
1427 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1428 final long id = addAppShortcut(db, childValues, parser);
1429 if (id >= 0) {
1430 folderItems.add(id);
1431 }
1432 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1433 final long id = addUriShortcut(db, childValues, res, parser);
1434 if (id >= 0) {
1435 folderItems.add(id);
1436 }
1437 } else {
1438 throw new RuntimeException("Folders can contain only shortcuts");
1439 }
1440 }
1441
1442 // We can only have folders with >= 2 items, so we need to remove the
1443 // folder and clean up if less than 2 items were included, or some
1444 // failed to add, and less than 2 were actually added
1445 if (folderItems.size() < 2 && folderId >= 0) {
1446 // Delete the folder
1447 deleteId(db, folderId);
1448
1449 // If we have a single item, promote it to where the folder
1450 // would have been.
1451 if (folderItems.size() == 1) {
1452 final ContentValues childValues = new ContentValues();
1453 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1454 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1455 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1456 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1457
1458 final long id = folderItems.get(0);
1459 db.update(TABLE_FAVORITES, childValues,
1460 LauncherSettings.Favorites._ID + "=" + id, null);
1461 } else {
1462 added = false;
1463 }
1464 }
1465 return added;
1466 }
1467
Jason Monk41314972014-03-03 16:11:30 -05001468 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1469 // logical choice for what shortcut should be used for that intent exists, then it is
1470 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001471 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1472 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001473 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001474 try {
Jason Monk41314972014-03-03 16:11:30 -05001475 metaIntent = Intent.parseUri(intentUri, 0);
1476 } catch (URISyntaxException e) {
1477 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1478 return -1;
1479 }
1480
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001481 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001482 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001483 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001484 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1485
1486 // Verify that the result is an app and not just the resolver dialog asking which
1487 // app to use.
1488 if (wouldLaunchResolverActivity(resolved, appList)) {
1489 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001490 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001491 if (systemApp == null) {
1492 // There is no logical choice for this meta-favorite, so rather than making
1493 // a bad choice just add nothing.
1494 Log.w(TAG, "No preference or single system activity found for "
1495 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001496 return -1;
1497 }
Jason Monk41314972014-03-03 16:11:30 -05001498 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001499 }
Jason Monk41314972014-03-03 16:11:30 -05001500 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001501 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001502 intent.setComponent(new ComponentName(info.packageName, info.name));
1503 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1504 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1505
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001506 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001507 }
1508
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001509 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001510 ResolveInfo systemResolve = null;
1511 final int N = appList.size();
1512 for (int i = 0; i < N; ++i) {
1513 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001514 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001515 appList.get(i).activityInfo.packageName, 0);
1516 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1517 if (systemResolve != null) {
1518 return null;
1519 } else {
1520 systemResolve = appList.get(i);
1521 }
1522 }
1523 } catch (PackageManager.NameNotFoundException e) {
1524 Log.w(TAG, "Unable to get info about resolve results", e);
1525 return null;
1526 }
1527 }
1528 return systemResolve;
1529 }
1530
1531 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1532 List<ResolveInfo> appList) {
1533 // If the list contains the above resolved activity, then it can't be
1534 // ResolverActivity itself.
1535 for (int i = 0; i < appList.size(); ++i) {
1536 ResolveInfo tmp = appList.get(i);
1537 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1538 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1539 return false;
1540 }
1541 }
1542 return true;
1543 }
1544
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001545 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1546 XmlResourceParser parser) {
1547 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1548 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1549 final String uri = getAttributeValue(parser, ATTR_URI);
1550
1551 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001552 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001553 try {
1554 ComponentName cn;
1555 try {
1556 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001557 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001558 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001559 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001560 new String[] { packageName });
1561 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001562 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001563 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001564 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001565 intent.setComponent(cn);
1566 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1567 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1568
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001569 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001570 intent);
1571 } catch (PackageManager.NameNotFoundException e) {
1572 Log.w(TAG, "Unable to add favorite: " + packageName +
1573 "/" + className, e);
1574 }
1575 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001576 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001577 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001578 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001579 } else {
1580 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1581 return -1;
1582 }
1583 }
1584
1585 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1586 Intent intent) {
1587 long id = generateNewItemId();
1588 values.put(Favorites.INTENT, intent.toUri(0));
1589 values.put(Favorites.TITLE, title);
1590 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1591 values.put(Favorites.SPANX, 1);
1592 values.put(Favorites.SPANY, 1);
1593 values.put(Favorites._ID, id);
1594 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1595 return -1;
1596 } else {
1597 return id;
1598 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001599 }
1600
1601 private long addFolder(SQLiteDatabase db, ContentValues values) {
1602 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1603 values.put(Favorites.SPANX, 1);
1604 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001605 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001606 values.put(Favorites._ID, id);
1607 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1608 return -1;
1609 } else {
1610 return id;
1611 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001612 }
1613
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001614 private ComponentName getSearchWidgetProvider() {
1615 SearchManager searchManager =
1616 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1617 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1618 if (searchComponent == null) return null;
1619 return getProviderInPackage(searchComponent.getPackageName());
1620 }
1621
1622 /**
1623 * Gets an appwidget provider from the given package. If the package contains more than
1624 * one appwidget provider, an arbitrary one is returned.
1625 */
1626 private ComponentName getProviderInPackage(String packageName) {
1627 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1628 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1629 if (providers == null) return null;
1630 final int providerCount = providers.size();
1631 for (int i = 0; i < providerCount; i++) {
1632 ComponentName provider = providers.get(i).provider;
1633 if (provider != null && provider.getPackageName().equals(packageName)) {
1634 return provider;
1635 }
1636 }
1637 return null;
1638 }
1639
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001640 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001641 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001642 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001643 }
1644
1645 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001646 ComponentName cn = new ComponentName("com.android.alarmclock",
1647 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001648 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001649 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001650
Winson Chungb3302ae2012-05-01 10:19:14 -07001651 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001652 SQLiteDatabase db, ContentValues values, TypedArray a)
1653 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001654
Mike Cleronb87bd162009-10-30 16:36:56 -07001655 String packageName = a.getString(R.styleable.Favorite_packageName);
1656 String className = a.getString(R.styleable.Favorite_className);
1657
1658 if (packageName == null || className == null) {
1659 return false;
1660 }
Romain Guy693599f2010-03-23 10:58:18 -07001661
1662 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001663 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001664 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001665 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001666 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001667 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001668 new String[] { packageName });
1669 cn = new ComponentName(packages[0], className);
1670 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001671 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001672 } catch (Exception e1) {
1673 hasPackage = false;
1674 }
1675 }
1676
1677 if (hasPackage) {
1678 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1679 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001680
1681 // Read the extras
1682 Bundle extras = new Bundle();
1683 int widgetDepth = parser.getDepth();
1684 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1685 parser.getDepth() > widgetDepth) {
1686 if (type != XmlPullParser.START_TAG) {
1687 continue;
1688 }
1689
1690 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1691 if (TAG_EXTRA.equals(parser.getName())) {
1692 String key = ar.getString(R.styleable.Extra_key);
1693 String value = ar.getString(R.styleable.Extra_value);
1694 if (key != null && value != null) {
1695 extras.putString(key, value);
1696 } else {
1697 throw new RuntimeException("Widget extras must have a key and value");
1698 }
1699 } else {
1700 throw new RuntimeException("Widgets can contain only extras");
1701 }
1702 ar.recycle();
1703 }
1704
1705 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001706 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001707
Romain Guy693599f2010-03-23 10:58:18 -07001708 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001709 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001710 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001711 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001712 boolean allocatedAppWidgets = false;
1713 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1714
1715 try {
1716 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001717
Mike Cleronb87bd162009-10-30 16:36:56 -07001718 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001719 values.put(Favorites.SPANX, spanX);
1720 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001721 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001722 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001723 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001724 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001725
1726 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001727
Michael Jurka8b805b12012-04-18 14:23:14 -07001728 // TODO: need to check return value
1729 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001730
1731 // Send a broadcast to configure the widget
1732 if (extras != null && !extras.isEmpty()) {
1733 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1734 intent.setComponent(cn);
1735 intent.putExtras(extras);
1736 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1737 mContext.sendBroadcast(intent);
1738 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001739 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001740 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001741 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001742
Mike Cleronb87bd162009-10-30 16:36:56 -07001743 return allocatedAppWidgets;
1744 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001745
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001746 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1747 XmlResourceParser parser) {
1748 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1749 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001750
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001751 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001752 String uri = null;
1753 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001754 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001755 intent = Intent.parseUri(uri, 0);
1756 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001757 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001758 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001759 }
1760
1761 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001762 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001763 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001764 }
1765
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001767 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1768 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001769 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001770 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1771 values.put(Favorites.SPANX, 1);
1772 values.put(Favorites.SPANY, 1);
1773 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001774 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1775 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001776 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001777
Adam Cohen228da5a2011-07-27 22:23:47 -07001778 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1779 return -1;
1780 }
1781 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001782 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001783
1784 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1785 final ContentResolver resolver = mContext.getContentResolver();
1786 Cursor c = null;
1787 int count = 0;
1788 int curScreen = 0;
1789
1790 try {
1791 c = resolver.query(uri, null, null, null, "title ASC");
1792 } catch (Exception e) {
1793 // Ignore
1794 }
1795
Dan Sandlerd5024042014-01-09 15:01:33 -05001796 // We already have a favorites database in the old provider
1797 if (c != null) {
1798 try {
1799 if (c.getCount() > 0) {
1800 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1801 final int intentIndex
1802 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1803 final int titleIndex
1804 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1805 final int iconTypeIndex
1806 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1807 final int iconIndex
1808 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1809 final int iconPackageIndex
1810 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1811 final int iconResourceIndex
1812 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1813 final int containerIndex
1814 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1815 final int itemTypeIndex
1816 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1817 final int screenIndex
1818 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1819 final int cellXIndex
1820 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1821 final int cellYIndex
1822 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1823 final int uriIndex
1824 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1825 final int displayModeIndex
1826 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001827 final int profileIndex
1828 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001829
1830 int i = 0;
1831 int curX = 0;
1832 int curY = 0;
1833
1834 final LauncherAppState app = LauncherAppState.getInstance();
1835 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1836 final int width = (int) grid.numColumns;
1837 final int height = (int) grid.numRows;
1838 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001839 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001840
1841 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1842
Adam Cohen72960972014-01-15 18:13:55 -08001843 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1844 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001845 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001846
1847 while (c.moveToNext()) {
1848 final int itemType = c.getInt(itemTypeIndex);
1849 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1850 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1851 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1852 continue;
1853 }
1854
1855 final int cellX = c.getInt(cellXIndex);
1856 final int cellY = c.getInt(cellYIndex);
1857 final int screen = c.getInt(screenIndex);
1858 int container = c.getInt(containerIndex);
1859 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001860
1861 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1862 UserHandleCompat userHandle;
1863 final long userSerialNumber;
1864 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1865 userSerialNumber = c.getInt(profileIndex);
1866 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1867 } else {
1868 // Default to the serial number of this user, for older
1869 // shortcuts.
1870 userHandle = UserHandleCompat.myUserHandle();
1871 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1872 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001873 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001874 + c.getString(titleIndex) + "\" ("
1875 + cellX + "," + cellY + "@"
1876 + LauncherSettings.Favorites.containerToString(container)
1877 + "/" + screen
1878 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001879
1880 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001881
1882 final Intent intent;
1883 final ComponentName cn;
1884 try {
1885 intent = Intent.parseUri(intentStr, 0);
1886 } catch (URISyntaxException e) {
1887 // bogus intent?
1888 Launcher.addDumpLog(TAG,
1889 "skipping invalid intent uri", true);
1890 continue;
1891 }
1892
1893 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001894 if (TextUtils.isEmpty(intentStr)) {
1895 // no intent? no icon
1896 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1897 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001898 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001899 !LauncherModel.isValidPackageActivity(mContext, cn,
1900 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001901 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001902 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001903 "no longer exists.", true);
1904 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001905 } else if (container ==
1906 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1907 // Dedupe icons directly on the workspace
1908
Adam Cohen556f6132014-01-15 15:18:08 -08001909 // Canonicalize
1910 // the Play Store sets the package parameter, but Launcher
1911 // does not, so we clear that out to keep them the same
1912 intent.setPackage(null);
1913 final String key = intent.toUri(0);
1914 if (seenIntents.contains(key)) {
1915 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001916 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001917 } else {
1918 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001919 }
1920 }
1921 }
1922
1923 ContentValues values = new ContentValues(c.getColumnCount());
1924 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1925 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1926 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1927 values.put(LauncherSettings.Favorites.ICON_TYPE,
1928 c.getInt(iconTypeIndex));
1929 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1930 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1931 c.getString(iconPackageIndex));
1932 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1933 c.getString(iconResourceIndex));
1934 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1935 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1936 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1937 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1938 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001939 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001940
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001941 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1942 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001943 }
1944
1945 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1946 // In a folder or in the hotseat, preserve position
1947 values.put(LauncherSettings.Favorites.SCREEN, screen);
1948 values.put(LauncherSettings.Favorites.CELLX, cellX);
1949 values.put(LauncherSettings.Favorites.CELLY, cellY);
1950 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001951 // For items contained directly on one of the workspace screen,
1952 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001953 }
1954
1955 values.put(LauncherSettings.Favorites.CONTAINER, container);
1956
Adam Cohen72960972014-01-15 18:13:55 -08001957 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1958 shortcuts.add(values);
1959 } else {
1960 folders.add(values);
1961 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001962 }
1963
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001964 // Now that we have all the hotseat icons, let's go through them left-right
1965 // and assign valid locations for them in the new hotseat
1966 final int N = hotseat.size();
1967 for (int idx=0; idx<N; idx++) {
1968 int hotseatX = hotseat.keyAt(idx);
1969 ContentValues values = hotseat.valueAt(idx);
1970
1971 if (hotseatX == grid.hotseatAllAppsRank) {
1972 // let's drop this in the next available hole in the hotseat
1973 while (++hotseatX < hotseatWidth) {
1974 if (hotseat.get(hotseatX) == null) {
1975 // found a spot! move it here
1976 values.put(LauncherSettings.Favorites.SCREEN,
1977 hotseatX);
1978 break;
1979 }
1980 }
1981 }
1982 if (hotseatX >= hotseatWidth) {
1983 // no room for you in the hotseat? it's off to the desktop with you
1984 values.put(LauncherSettings.Favorites.CONTAINER,
1985 Favorites.CONTAINER_DESKTOP);
1986 }
1987 }
1988
Adam Cohen72960972014-01-15 18:13:55 -08001989 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1990 // Folders first
1991 allItems.addAll(folders);
1992 // Then shortcuts
1993 allItems.addAll(shortcuts);
1994
1995 // Layout all the folders
1996 for (ContentValues values: allItems) {
1997 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1998 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1999 // Hotseat items and folder items have already had their
2000 // location information set. Nothing to be done here.
2001 continue;
2002 }
2003 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2004 values.put(LauncherSettings.Favorites.CELLX, curX);
2005 values.put(LauncherSettings.Favorites.CELLY, curY);
2006 curX = (curX + 1) % width;
2007 if (curX == 0) {
2008 curY = (curY + 1);
2009 }
2010 // Leave the last row of icons blank on every screen
2011 if (curY == height - 1) {
2012 curScreen = (int) generateNewScreenId();
2013 curY = 0;
2014 }
2015 }
2016
2017 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002018 db.beginTransaction();
2019 try {
Adam Cohen72960972014-01-15 18:13:55 -08002020 for (ContentValues row: allItems) {
2021 if (row == null) continue;
2022 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002023 < 0) {
2024 return;
2025 } else {
2026 count++;
2027 }
2028 }
2029 db.setTransactionSuccessful();
2030 } finally {
2031 db.endTransaction();
2032 }
2033 }
2034
2035 db.beginTransaction();
2036 try {
2037 for (i=0; i<=curScreen; i++) {
2038 final ContentValues values = new ContentValues();
2039 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2040 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2041 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2042 < 0) {
2043 return;
2044 }
2045 }
2046 db.setTransactionSuccessful();
2047 } finally {
2048 db.endTransaction();
2049 }
2050 }
2051 } finally {
2052 c.close();
2053 }
2054 }
2055
2056 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2057 + (curScreen+1) + " screens", true);
2058
2059 // ensure that new screens are created to hold these icons
2060 setFlagJustLoadedOldDb();
2061
2062 // Update max IDs; very important since we just grabbed IDs from another database
2063 mMaxItemId = initializeMaxItemId(db);
2064 mMaxScreenId = initializeMaxScreenId(db);
2065 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2066 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002067 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002068
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002069 /**
2070 * Build a query string that will match any row where the column matches
2071 * anything in the values list.
2072 */
2073 static String buildOrWhereString(String column, int[] values) {
2074 StringBuilder selectWhere = new StringBuilder();
2075 for (int i = values.length - 1; i >= 0; i--) {
2076 selectWhere.append(column).append("=").append(values[i]);
2077 if (i > 0) {
2078 selectWhere.append(" OR ");
2079 }
2080 }
2081 return selectWhere.toString();
2082 }
2083
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002084 /**
2085 * Return attribute value, attempting launcher-specific namespace first
2086 * before falling back to anonymous attribute.
2087 */
2088 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2089 String value = parser.getAttributeValue(
2090 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2091 if (value == null) {
2092 value = parser.getAttributeValue(null, attribute);
2093 }
2094 return value;
2095 }
2096
2097 /**
2098 * Return attribute resource value, attempting launcher-specific namespace
2099 * first before falling back to anonymous attribute.
2100 */
2101 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2102 int defaultValue) {
2103 int value = parser.getAttributeResourceValue(
2104 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2105 defaultValue);
2106 if (value == defaultValue) {
2107 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2108 }
2109 return value;
2110 }
2111
2112 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2113 to.put(key, from.getAsInteger(key));
2114 }
2115
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002116 static class SqlArguments {
2117 public final String table;
2118 public final String where;
2119 public final String[] args;
2120
2121 SqlArguments(Uri url, String where, String[] args) {
2122 if (url.getPathSegments().size() == 1) {
2123 this.table = url.getPathSegments().get(0);
2124 this.where = where;
2125 this.args = args;
2126 } else if (url.getPathSegments().size() != 2) {
2127 throw new IllegalArgumentException("Invalid URI: " + url);
2128 } else if (!TextUtils.isEmpty(where)) {
2129 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2130 } else {
2131 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002132 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002133 this.args = null;
2134 }
2135 }
2136
2137 SqlArguments(Uri url) {
2138 if (url.getPathSegments().size() == 1) {
2139 table = url.getPathSegments().get(0);
2140 where = null;
2141 args = null;
2142 } else {
2143 throw new IllegalArgumentException("Invalid URI: " + url);
2144 }
2145 }
2146 }
Adam Cohen72960972014-01-15 18:13:55 -08002147}