blob: ad43cba486883233c6dbc9690c4856ddf0af751e [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000019import android.app.SearchManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000022import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080023import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070024import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000025import android.content.ContentProviderOperation;
26import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000032import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070033import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ActivityInfo;
Jason Monk41314972014-03-03 16:11:30 -050035import android.content.pm.ApplicationInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.content.pm.PackageManager;
Jason Monk41314972014-03-03 16:11:30 -050037import android.content.pm.ResolveInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.database.Cursor;
42import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteDatabase;
44import android.database.sqlite.SQLiteOpenHelper;
45import android.database.sqlite.SQLiteQueryBuilder;
46import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080047import android.graphics.Bitmap;
48import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070049import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070050import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070051import android.provider.Settings;
52import android.text.TextUtils;
53import android.util.AttributeSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080054import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050055import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070057
Daniel Sandler325dc232013-06-05 22:57:57 -040058import com.android.launcher3.LauncherSettings.Favorites;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070060
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Dan Sandlerd5024042014-01-09 15:01:33 -050068import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000069import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080072 private static final String TAG = "Launcher.LauncherProvider";
73 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
75 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070076
Adam Cohen119285e2014-04-02 16:59:08 -070077 private static final int DATABASE_VERSION = 18;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Adam Cohene25af792013-06-06 23:08:25 -070079 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040080 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070081
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050082 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050083 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050084
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070086 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070088 static final String UPGRADED_FROM_OLD_DATABASE =
89 "UPGRADED_FROM_OLD_DATABASE";
90 static final String EMPTY_DATABASE_CREATED =
91 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020092 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
93 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Winson Chungb3302ae2012-05-01 10:19:14 -070095 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070096 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070097
Anjali Koppal67e7cae2014-03-13 12:14:12 -070098 private LauncherProviderChangeListener mListener;
99
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700100 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700101 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700102 * {@link AppWidgetHost#deleteHost()} is called during database creation.
103 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
104 */
105 static final Uri CONTENT_APPWIDGET_RESET_URI =
106 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700107
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700108 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700109 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
111 @Override
112 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400113 final Context context = getContext();
114 mOpenHelper = new DatabaseHelper(context);
115 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116 return true;
117 }
118
Winson Chung0b560dd2014-01-21 13:00:26 -0800119 public boolean wasNewDbCreated() {
120 return mOpenHelper.wasNewDbCreated();
121 }
122
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700123 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
124 mListener = listener;
125 }
126
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127 @Override
128 public String getType(Uri uri) {
129 SqlArguments args = new SqlArguments(uri, null, null);
130 if (TextUtils.isEmpty(args.where)) {
131 return "vnd.android.cursor.dir/" + args.table;
132 } else {
133 return "vnd.android.cursor.item/" + args.table;
134 }
135 }
136
137 @Override
138 public Cursor query(Uri uri, String[] projection, String selection,
139 String[] selectionArgs, String sortOrder) {
140
141 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
142 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
143 qb.setTables(args.table);
144
Romain Guy73b979d2009-06-09 12:57:21 -0700145 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800146 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
147 result.setNotificationUri(getContext().getContentResolver(), uri);
148
149 return result;
150 }
151
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 private static long dbInsertAndCheck(DatabaseHelper helper,
153 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500154 if (values == null) {
155 throw new RuntimeException("Error: attempting to insert null values");
156 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500157 if (!values.containsKey(LauncherSettings.BaseLauncherColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 throw new RuntimeException("Error: attempting to add item without specifying an id");
159 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500160 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 return db.insert(table, nullColumnHack, values);
162 }
163
Adam Cohen228da5a2011-07-27 22:23:47 -0700164 private static void deleteId(SQLiteDatabase db, long id) {
165 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
166 SqlArguments args = new SqlArguments(uri, null, null);
167 db.delete(args.table, args.where, args.args);
168 }
169
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 @Override
171 public Uri insert(Uri uri, ContentValues initialValues) {
172 SqlArguments args = new SqlArguments(uri);
173
174 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400175 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700176 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177 if (rowId <= 0) return null;
178
179 uri = ContentUris.withAppendedId(uri, rowId);
180 sendNotify(uri);
181
182 return uri;
183 }
184
185 @Override
186 public int bulkInsert(Uri uri, ContentValues[] values) {
187 SqlArguments args = new SqlArguments(uri);
188
189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
190 db.beginTransaction();
191 try {
192 int numValues = values.length;
193 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400194 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700195 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
196 return 0;
197 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198 }
199 db.setTransactionSuccessful();
200 } finally {
201 db.endTransaction();
202 }
203
204 sendNotify(uri);
205 return values.length;
206 }
207
208 @Override
Yura085c8532014-02-11 15:15:29 +0000209 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
210 throws OperationApplicationException {
211 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
212 db.beginTransaction();
213 try {
214 ContentProviderResult[] result = super.applyBatch(operations);
215 db.setTransactionSuccessful();
216 return result;
217 } finally {
218 db.endTransaction();
219 }
220 }
221
222 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223 public int delete(Uri uri, String selection, String[] selectionArgs) {
224 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
225
226 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
227 int count = db.delete(args.table, args.where, args.args);
228 if (count > 0) sendNotify(uri);
229
230 return count;
231 }
232
233 @Override
234 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
235 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
236
Chris Wren1ada10d2013-09-13 18:01:38 -0400237 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
239 int count = db.update(args.table, values, args.where, args.args);
240 if (count > 0) sendNotify(uri);
241
242 return count;
243 }
244
245 private void sendNotify(Uri uri) {
246 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
247 if (notify == null || "true".equals(notify)) {
248 getContext().getContentResolver().notifyChange(uri, null);
249 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400250
251 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400252 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700253 if (mListener != null) {
254 mListener.onLauncherProviderChange();
255 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400256 }
257
258 private void addModifiedTime(ContentValues values) {
259 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800260 }
261
Adam Cohendcd297f2013-06-18 13:13:40 -0700262 public long generateNewItemId() {
263 return mOpenHelper.generateNewItemId();
264 }
265
Winson Chungc763c4e2013-07-19 13:49:06 -0700266 public void updateMaxItemId(long id) {
267 mOpenHelper.updateMaxItemId(id);
268 }
269
Adam Cohendcd297f2013-06-18 13:13:40 -0700270 public long generateNewScreenId() {
271 return mOpenHelper.generateNewScreenId();
272 }
273
274 // This is only required one time while loading the workspace during the
275 // upgrade path, and should never be called from anywhere else.
276 public void updateMaxScreenId(long maxScreenId) {
277 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700278 }
279
Brian Muramatsu5524b492012-10-02 16:55:54 -0700280 /**
Adam Cohene25af792013-06-06 23:08:25 -0700281 * @param Should we load the old db for upgrade? first run only.
282 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700283 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400284 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700285 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
286
Winson Chungc763c4e2013-07-19 13:49:06 -0700287 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700288
Winson Chungc763c4e2013-07-19 13:49:06 -0700289 sJustLoadedFromOldDb = false;
290 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700291
292 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700293 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700294 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700295 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700296 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700297 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700298 }
299
300 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700301 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
302 */
Michael Jurka45355c42012-10-08 13:21:35 +0200303 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400304 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700305 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700306
Winson Chungc763c4e2013-07-19 13:49:06 -0700307 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500308 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200309 int workspaceResId = origWorkspaceResId;
310
Brian Muramatsu5524b492012-10-02 16:55:54 -0700311 // Use default workspace resource if none provided
312 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800313 workspaceResId =
314 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700315 }
316
Michael Jurkab85f8a42012-04-25 15:48:32 -0700317 // Populate favorites table with initial favorites
318 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700319 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200320 if (origWorkspaceResId != 0) {
321 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
322 }
Adam Cohene25af792013-06-06 23:08:25 -0700323
Brian Muramatsu5524b492012-10-02 16:55:54 -0700324 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700325 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700326 editor.commit();
327 }
328 }
329
Dan Sandlerd5024042014-01-09 15:01:33 -0500330 public void migrateLauncher2Shortcuts() {
331 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
332 LauncherSettings.Favorites.OLD_CONTENT_URI);
333 }
334
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800335 private static int getDefaultWorkspaceResourceId() {
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800336 if (LauncherAppState.isDisableAllApps()) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800337 return R.xml.default_workspace_no_all_apps;
338 } else {
339 return R.xml.default_workspace;
340 }
341 }
342
Winson Chungc763c4e2013-07-19 13:49:06 -0700343 private static interface ContentValuesCallback {
344 public void onRow(ContentValues values);
345 }
346
Adam Cohen6dbe0492013-12-02 17:00:14 -0800347 private static boolean shouldImportLauncher2Database(Context context) {
348 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
349
350 // We don't import the old databse for tablets, as the grid size has changed.
351 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
352 }
353
Dan Sandlerd5024042014-01-09 15:01:33 -0500354 public void deleteDatabase() {
355 // Are you sure? (y/n)
356 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500357 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500358 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500359 if (dbFile.exists()) {
360 SQLiteDatabase.deleteDatabase(dbFile);
361 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500362 mOpenHelper = new DatabaseHelper(getContext());
363 }
364
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800365 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500366 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 private static final String TAG_FAVORITES = "favorites";
368 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700369 private static final String TAG_CLOCK = "clock";
370 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700371 private static final String TAG_APPWIDGET = "appwidget";
372 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700373 private static final String TAG_FOLDER = "folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700374 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400375 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700376
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800377 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700378 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700379 private long mMaxItemId = -1;
380 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800381
Winson Chung0b560dd2014-01-21 13:00:26 -0800382 private boolean mNewDbCreated = false;
383
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800384 DatabaseHelper(Context context) {
385 super(context, DATABASE_NAME, null, DATABASE_VERSION);
386 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700387 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700388
389 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
390 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700391 if (mMaxItemId == -1) {
392 mMaxItemId = initializeMaxItemId(getWritableDatabase());
393 }
394 if (mMaxScreenId == -1) {
395 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700396 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 }
398
Winson Chung0b560dd2014-01-21 13:00:26 -0800399 public boolean wasNewDbCreated() {
400 return mNewDbCreated;
401 }
402
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700403 /**
404 * Send notification that we've deleted the {@link AppWidgetHost},
405 * probably as part of the initial database creation. The receiver may
406 * want to re-call {@link AppWidgetHost#startListening()} to ensure
407 * callbacks are correctly set.
408 */
409 private void sendAppWidgetResetNotify() {
410 final ContentResolver resolver = mContext.getContentResolver();
411 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
412 }
413
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800414 @Override
415 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800416 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700417
Adam Cohendcd297f2013-06-18 13:13:40 -0700418 mMaxItemId = 1;
419 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800420 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700421
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800422 db.execSQL("CREATE TABLE favorites (" +
423 "_id INTEGER PRIMARY KEY," +
424 "title TEXT," +
425 "intent TEXT," +
426 "container INTEGER," +
427 "screen INTEGER," +
428 "cellX INTEGER," +
429 "cellY INTEGER," +
430 "spanX INTEGER," +
431 "spanY INTEGER," +
432 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700433 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800434 "isShortcut INTEGER," +
435 "iconType INTEGER," +
436 "iconPackage TEXT," +
437 "iconResource TEXT," +
438 "icon BLOB," +
439 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400440 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400441 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500442 "modified INTEGER NOT NULL DEFAULT 0," +
443 "restored INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800444 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700445 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800446
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700447 // Database was just created, so wipe any previous widgets
448 if (mAppWidgetHost != null) {
449 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700450 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800451 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700452
Adam Cohen6dbe0492013-12-02 17:00:14 -0800453 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500454 // Try converting the old database
455 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
456 public void onRow(ContentValues values) {
457 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
458 if (container == Favorites.CONTAINER_DESKTOP) {
459 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
460 screen = (int) upgradeLauncherDb_permuteScreens(screen);
461 values.put(LauncherSettings.Favorites.SCREEN, screen);
462 }
463 }
464 };
465 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
466 "/old_favorites?notify=true");
467 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
468 // Try and upgrade from the Launcher2 db
469 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
470 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
471 // If we fail, then set a flag to load the default workspace
472 setFlagEmptyDbCreated();
473 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 }
475 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500476 // Right now, in non-default workspace cases, we want to run the final
477 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
478 // set that flag too.
479 setFlagJustLoadedOldDb();
480 } else {
481 // Fresh and clean launcher DB.
482 mMaxItemId = initializeMaxItemId(db);
483 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 }
485 }
486
Adam Cohendcd297f2013-06-18 13:13:40 -0700487 private void addWorkspacesTable(SQLiteDatabase db) {
488 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
489 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
491 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700492 ");");
493 }
494
Adam Cohen119285e2014-04-02 16:59:08 -0700495 private void removeOrphanedItems(SQLiteDatabase db) {
496 db.execSQL("DELETE FROM " + TABLE_FAVORITES + " WHERE " +
497 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
498 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS +
499 ")");
500 }
501
Winson Chungc763c4e2013-07-19 13:49:06 -0700502 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400503 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700504 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
505 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700506 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
507 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700508 editor.commit();
509 }
510
Winson Chungc763c4e2013-07-19 13:49:06 -0700511 private void setFlagEmptyDbCreated() {
512 String spKey = LauncherAppState.getSharedPreferencesKey();
513 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
514 SharedPreferences.Editor editor = sp.edit();
515 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
516 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
517 editor.commit();
518 }
519
520 // We rearrange the screens from the old launcher
521 // 12345 -> 34512
522 private long upgradeLauncherDb_permuteScreens(long screen) {
523 if (screen >= 2) {
524 return screen - 2;
525 } else {
526 return screen + 3;
527 }
528 }
529
530 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
531 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800532 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800533 boolean converted = false;
534
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800535 final ContentResolver resolver = mContext.getContentResolver();
536 Cursor cursor = null;
537
538 try {
539 cursor = resolver.query(uri, null, null, null, null);
540 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700541 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 }
543
544 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700545 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700547 if (cursor.getCount() > 0) {
548 converted = copyFromCursor(db, cursor, cb) > 0;
549 if (converted && deleteRows) {
550 resolver.delete(uri, null, null);
551 }
552 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800553 } finally {
554 cursor.close();
555 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800556 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700557
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800558 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700559 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800560 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700562
563 // Update max item id
564 mMaxItemId = initializeMaxItemId(db);
565 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800566 }
567
568 return converted;
569 }
570
Winson Chungc763c4e2013-07-19 13:49:06 -0700571 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700572 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
574 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
575 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
576 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
577 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
578 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
579 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
580 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
581 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
582 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
583 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
584 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
585 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
586
587 ContentValues[] rows = new ContentValues[c.getCount()];
588 int i = 0;
589 while (c.moveToNext()) {
590 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700591 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800592 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
593 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
594 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
595 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
596 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
597 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
598 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
599 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700600 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
602 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
603 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
604 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
605 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700606 if (cb != null) {
607 cb.onRow(values);
608 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609 rows[i++] = values;
610 }
611
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700613 if (i > 0) {
614 db.beginTransaction();
615 try {
616 int numValues = rows.length;
617 for (i = 0; i < numValues; i++) {
618 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
619 return 0;
620 } else {
621 total++;
622 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700624 db.setTransactionSuccessful();
625 } finally {
626 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 }
629
630 return total;
631 }
632
633 @Override
634 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700635 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700636
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700638 if (version < 3) {
639 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 db.beginTransaction();
641 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700642 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800643 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700644 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700646 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 } catch (SQLException ex) {
648 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800649 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 } finally {
651 db.endTransaction();
652 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700653
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700655 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800656 convertWidgets(db);
657 }
658 }
Romain Guy73b979d2009-06-09 12:57:21 -0700659
660 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800661 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700662 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700663
Romain Guy509cd6a2010-03-23 15:10:56 -0700664 // Where's version 5?
665 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400666 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700667 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
668 // but version 5 on there was the updateContactsShortcuts change
669 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
670 // The updateContactsShortcuts change is idempotent, so running it twice
671 // is okay so we'll do that when upgrading the devices that shipped with it.
672 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800673 // We went from 3 to 5 screens. Move everything 1 to the right
674 db.beginTransaction();
675 try {
676 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
677 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800678 } catch (SQLException ex) {
679 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800680 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800681 } finally {
682 db.endTransaction();
683 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700684
Romain Guy509cd6a2010-03-23 15:10:56 -0700685 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800686 if (updateContactsShortcuts(db)) {
687 version = 6;
688 }
689 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000690
691 if (version < 7) {
692 // Version 7 gets rid of the special search widget.
693 convertWidgets(db);
694 version = 7;
695 }
696
Joe Onorato0589f0f2010-02-08 13:44:00 -0800697 if (version < 8) {
698 // Version 8 (froyo) has the icons all normalized. This should
699 // already be the case in practice, but we now rely on it and don't
700 // resample the images each time.
701 normalizeIcons(db);
702 version = 8;
703 }
704
Winson Chung3d503fb2011-07-13 17:25:49 -0700705 if (version < 9) {
706 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
707 // 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 -0700708 if (mMaxItemId == -1) {
709 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700710 }
711
712 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800713 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700714 version = 9;
715 }
716
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700717 // We bumped the version three time during JB, once to update the launch flags, once to
718 // update the override for the default launch animation and once to set the mimetype
719 // to improve startup performance
720 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700721 // Contact shortcuts need a different set of flags to be launched now
722 // The updateContactsShortcuts change is idempotent, so we can keep using it like
723 // back in the Donut days
724 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700725 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700726 }
727
Adam Cohendcd297f2013-06-18 13:13:40 -0700728 if (version < 13) {
729 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
730 // to persist workspace screens and their relative order.
731 mMaxScreenId = 0;
732
733 // This will never happen in the wild, but when we switch to using workspace
734 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700735 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700736
737 addWorkspacesTable(db);
738 version = 13;
739 }
740
Chris Wrend5e66bf2013-09-16 14:02:29 -0400741 if (version < 14) {
742 db.beginTransaction();
743 try {
744 // Insert new column for holding widget provider name
745 db.execSQL("ALTER TABLE favorites " +
746 "ADD COLUMN appWidgetProvider TEXT;");
747 db.setTransactionSuccessful();
748 version = 14;
749 } catch (SQLException ex) {
750 // Old version remains, which means we wipe old data
751 Log.e(TAG, ex.getMessage(), ex);
752 } finally {
753 db.endTransaction();
754 }
755 }
756
Chris Wren1ada10d2013-09-13 18:01:38 -0400757 if (version < 15) {
758 db.beginTransaction();
759 try {
760 // Insert new column for holding update timestamp
761 db.execSQL("ALTER TABLE favorites " +
762 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
763 db.execSQL("ALTER TABLE workspaceScreens " +
764 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
765 db.setTransactionSuccessful();
766 version = 15;
767 } catch (SQLException ex) {
768 // Old version remains, which means we wipe old data
769 Log.e(TAG, ex.getMessage(), ex);
770 } finally {
771 db.endTransaction();
772 }
773 }
774
Chris Wrenf4d08112014-01-16 18:13:56 -0500775
776 if (version < 16) {
777 db.beginTransaction();
778 try {
779 // Insert new column for holding restore status
780 db.execSQL("ALTER TABLE favorites " +
781 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
782 db.setTransactionSuccessful();
783 version = 16;
784 } catch (SQLException ex) {
785 // Old version remains, which means we wipe old data
786 Log.e(TAG, ex.getMessage(), ex);
787 } finally {
788 db.endTransaction();
789 }
790 }
791
Adam Cohen71e03b92014-02-21 14:09:53 -0800792 if (version < 17) {
793 // We use the db version upgrade here to identify users who may not have seen
794 // clings yet (because they weren't available), but for whom the clings are now
795 // available (tablet users). Because one of the possible cling flows (migration)
796 // is very destructive (wipes out workspaces), we want to prevent this from showing
797 // until clear data. We do so by marking that the clings have been shown.
798 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
799 version = 17;
800 }
801
Adam Cohen119285e2014-04-02 16:59:08 -0700802 if (version < 18) {
803 // Due to a data loss bug, some users may have items associated with screen ids
804 // which no longer exist. Since this can cause other problems, and since the user
805 // will never see these items anyway, we use database upgrade as an opportunity to
806 // clean things up.
Adam Cohena7946072014-04-10 18:06:59 -0700807
808 // TODO: this needs to be fixed, currently causes data loss.
809 //removeOrphanedItems(db);
Adam Cohen119285e2014-04-02 16:59:08 -0700810 version = 18;
811 }
812
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800813 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800814 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800815 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
817
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800818 onCreate(db);
819 }
820 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800821
822 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800823 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
824 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
825
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700826 Cursor c = null;
827 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800828 db.beginTransaction();
829 try {
830 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700831 c = db.query(TABLE_FAVORITES,
832 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800833 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700834 if (c == null) return false;
835
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800836 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700837
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800838 final int idIndex = c.getColumnIndex(Favorites._ID);
839 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700840
841 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800842 long favoriteId = c.getLong(idIndex);
843 final String intentUri = c.getString(intentIndex);
844 if (intentUri != null) {
845 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700846 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800847 android.util.Log.d("Home", intent.toString());
848 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700849 if (uri != null) {
850 final String data = uri.toString();
851 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
852 actionQuickContact.equals(intent.getAction())) &&
853 (data.startsWith("content://contacts/people/") ||
854 data.startsWith("content://com.android.contacts/" +
855 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800856
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700857 final Intent newIntent = new Intent(actionQuickContact);
858 // When starting from the launcher, start in a new, cleared task
859 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
860 // clear the whole thing preemptively here since
861 // QuickContactActivity will finish itself when launching other
862 // detail activities.
863 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
864 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700865 newIntent.putExtra(
866 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700867 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700868 // Determine the type and also put that in the shortcut
869 // (that can speed up launch a bit)
870 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800871
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700872 final ContentValues values = new ContentValues();
873 values.put(LauncherSettings.Favorites.INTENT,
874 newIntent.toUri(0));
875
876 String updateWhere = Favorites._ID + "=" + favoriteId;
877 db.update(TABLE_FAVORITES, values, updateWhere, null);
878 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800879 }
880 } catch (RuntimeException ex) {
881 Log.e(TAG, "Problem upgrading shortcut", ex);
882 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700883 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800884 }
885 }
886 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700887
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
890 Log.w(TAG, "Problem while upgrading contacts", ex);
891 return false;
892 } finally {
893 db.endTransaction();
894 if (c != null) {
895 c.close();
896 }
897 }
898
899 return true;
900 }
901
Joe Onorato0589f0f2010-02-08 13:44:00 -0800902 private void normalizeIcons(SQLiteDatabase db) {
903 Log.d(TAG, "normalizing icons");
904
Joe Onorato346e1292010-02-18 10:34:24 -0500905 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800906 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400907 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800908 try {
909 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400910 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600911 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800912
913 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
914 Favorites.ICON_TYPE_BITMAP, null);
915
916 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
917 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
918
919 while (c.moveToNext()) {
920 long id = c.getLong(idIndex);
921 byte[] data = c.getBlob(iconIndex);
922 try {
923 Bitmap bitmap = Utilities.resampleIconBitmap(
924 BitmapFactory.decodeByteArray(data, 0, data.length),
925 mContext);
926 if (bitmap != null) {
927 update.bindLong(1, id);
928 data = ItemInfo.flattenBitmap(bitmap);
929 if (data != null) {
930 update.bindBlob(2, data);
931 update.execute();
932 }
933 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800934 }
935 } catch (Exception e) {
936 if (!logged) {
937 Log.e(TAG, "Failed normalizing icon " + id, e);
938 } else {
939 Log.e(TAG, "Also failed normalizing icon " + id);
940 }
941 logged = true;
942 }
943 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000944 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800945 } catch (SQLException ex) {
946 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
947 } finally {
948 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400949 if (update != null) {
950 update.close();
951 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800952 if (c != null) {
953 c.close();
954 }
955 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700956 }
957
958 // Generates a new ID to use for an object in your database. This method should be only
959 // called from the main UI thread. As an exception, we do call it when we call the
960 // constructor from the worker thread; however, this doesn't extend until after the
961 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
962 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700963 public long generateNewItemId() {
964 if (mMaxItemId < 0) {
965 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700966 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700967 mMaxItemId += 1;
968 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700969 }
970
Winson Chungc763c4e2013-07-19 13:49:06 -0700971 public void updateMaxItemId(long id) {
972 mMaxItemId = id + 1;
973 }
974
Chris Wren5dee7af2013-12-20 17:22:11 -0500975 public void checkId(String table, ContentValues values) {
976 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
977 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
978 mMaxScreenId = Math.max(id, mMaxScreenId);
979 } else {
980 mMaxItemId = Math.max(id, mMaxItemId);
981 }
982 }
983
Adam Cohendcd297f2013-06-18 13:13:40 -0700984 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700985 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
986
987 // get the result
988 final int maxIdIndex = 0;
989 long id = -1;
990 if (c != null && c.moveToNext()) {
991 id = c.getLong(maxIdIndex);
992 }
Michael Jurka5130e402011-10-13 04:55:35 -0700993 if (c != null) {
994 c.close();
995 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700996
997 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 throw new RuntimeException("Error: could not query max item id");
999 }
1000
1001 return id;
1002 }
1003
1004 // Generates a new ID to use for an workspace screen in your database. This method
1005 // should be only called from the main UI thread. As an exception, we do call it when we
1006 // call the constructor from the worker thread; however, this doesn't extend until after the
1007 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1008 // after that point
1009 public long generateNewScreenId() {
1010 if (mMaxScreenId < 0) {
1011 throw new RuntimeException("Error: max screen id was not initialized");
1012 }
1013 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001014 // Log to disk
1015 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 return mMaxScreenId;
1017 }
1018
1019 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001020 // Log to disk
1021 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 mMaxScreenId = maxScreenId;
1023 }
1024
1025 private long initializeMaxScreenId(SQLiteDatabase db) {
1026 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1027
1028 // get the result
1029 final int maxIdIndex = 0;
1030 long id = -1;
1031 if (c != null && c.moveToNext()) {
1032 id = c.getLong(maxIdIndex);
1033 }
1034 if (c != null) {
1035 c.close();
1036 }
1037
1038 if (id == -1) {
1039 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001040 }
1041
Winson Chunga90303b2013-11-15 13:05:06 -08001042 // Log to disk
1043 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001045 }
1046
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001047 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001048 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001049 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001050 */
1051 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001052 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001053 final int[] bindSources = new int[] {
1054 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1055 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001056 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001057 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001058
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001059 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001060
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001061 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001062
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001063 db.beginTransaction();
1064 try {
1065 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001066 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001067 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001068
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001069 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001070
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001071 final ContentValues values = new ContentValues();
1072 while (c != null && c.moveToNext()) {
1073 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001074 int favoriteType = c.getInt(1);
1075
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001076 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001077 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001078 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001079
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001080 if (LOGD) {
1081 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1082 + " for favoriteId=" + favoriteId);
1083 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001084 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001085 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1086 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1087
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001088 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001089 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1090 values.put(LauncherSettings.Favorites.SPANX, 4);
1091 values.put(LauncherSettings.Favorites.SPANY, 1);
1092 } else {
1093 values.put(LauncherSettings.Favorites.SPANX, 2);
1094 values.put(LauncherSettings.Favorites.SPANY, 2);
1095 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001096
1097 String updateWhere = Favorites._ID + "=" + favoriteId;
1098 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001099
Bjorn Bringert34251342009-12-15 13:33:11 +00001100 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001101 // TODO: check return value
1102 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001103 new ComponentName("com.android.alarmclock",
1104 "com.android.alarmclock.AnalogAppWidgetProvider"));
1105 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001106 // TODO: check return value
1107 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001108 new ComponentName("com.android.camera",
1109 "com.android.camera.PhotoAppWidgetProvider"));
1110 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001111 // TODO: check return value
1112 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001113 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001114 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001115 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001116 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001117 }
1118 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001119
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001120 db.setTransactionSuccessful();
1121 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001122 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001123 } finally {
1124 db.endTransaction();
1125 if (c != null) {
1126 c.close();
1127 }
1128 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001129
1130 // Update max item id
1131 mMaxItemId = initializeMaxItemId(db);
1132 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001133 }
1134
Michael Jurka8b805b12012-04-18 14:23:14 -07001135 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1136 throws XmlPullParserException, IOException {
1137 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001138 while ((type = parser.next()) != XmlPullParser.START_TAG
1139 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001140 ;
1141 }
1142
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001143 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001144 throw new XmlPullParserException("No start tag found");
1145 }
1146
1147 if (!parser.getName().equals(firstElementName)) {
1148 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1149 ", expected " + firstElementName);
1150 }
1151 }
1152
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001153 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154 * Loads the default set of favorite packages from an xml file.
1155 *
1156 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001157 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001158 */
Winson Chung6d092682011-11-16 18:43:26 -08001159 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001160 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1161 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1162 ContentValues values = new ContentValues();
1163
Daniel Sandler57dac262013-10-03 13:28:36 -04001164 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1165
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001166 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001167 int i = 0;
1168 try {
Winson Chung6d092682011-11-16 18:43:26 -08001169 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001170 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001171 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001172
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001173 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001174
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001175 int type;
1176 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1177 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1178
1179 if (type != XmlPullParser.START_TAG) {
1180 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 }
1182
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001183 boolean added = false;
1184 final String name = parser.getName();
1185
Daniel Sandler57dac262013-10-03 13:28:36 -04001186 if (TAG_INCLUDE.equals(name)) {
1187 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1188
1189 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1190
1191 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1192 "", resId));
1193
1194 if (resId != 0 && resId != workspaceResourceId) {
1195 // recursively load some more favorites, why not?
1196 i += loadFavorites(db, resId);
1197 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001198 } else {
1199 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1200 }
1201
1202 a.recycle();
1203
1204 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1205 continue;
1206 }
1207
1208 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001209 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1210
Winson Chung3d503fb2011-07-13 17:25:49 -07001211 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1212 if (a.hasValue(R.styleable.Favorite_container)) {
1213 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1214 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001215
Winson Chung6d092682011-11-16 18:43:26 -08001216 String screen = a.getString(R.styleable.Favorite_screen);
1217 String x = a.getString(R.styleable.Favorite_x);
1218 String y = a.getString(R.styleable.Favorite_y);
1219
Winson Chung6d092682011-11-16 18:43:26 -08001220 values.clear();
1221 values.put(LauncherSettings.Favorites.CONTAINER, container);
1222 values.put(LauncherSettings.Favorites.SCREEN, screen);
1223 values.put(LauncherSettings.Favorites.CELLX, x);
1224 values.put(LauncherSettings.Favorites.CELLY, y);
1225
Daniel Sandler57dac262013-10-03 13:28:36 -04001226 if (LOGD) {
1227 final String title = a.getString(R.styleable.Favorite_title);
1228 final String pkg = a.getString(R.styleable.Favorite_packageName);
1229 final String something = title != null ? title : pkg;
1230 Log.v(TAG, String.format(
1231 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1232 "", name,
1233 (something == null ? "" : (" \"" + something + "\"")),
1234 container, screen, x, y));
1235 }
1236
Winson Chung6d092682011-11-16 18:43:26 -08001237 if (TAG_FAVORITE.equals(name)) {
1238 long id = addAppShortcut(db, values, a, packageManager, intent);
1239 added = id >= 0;
1240 } else if (TAG_SEARCH.equals(name)) {
1241 added = addSearchWidget(db, values);
1242 } else if (TAG_CLOCK.equals(name)) {
1243 added = addClockWidget(db, values);
1244 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001245 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001246 } else if (TAG_SHORTCUT.equals(name)) {
1247 long id = addUriShortcut(db, values, a);
1248 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001249 } else if (TAG_RESOLVE.equals(name)) {
1250 // This looks through the contained favorites (or meta-favorites) and
1251 // attempts to add them as shortcuts in the fallback group's location
1252 // until one is added successfully.
1253 added = false;
1254 final int groupDepth = parser.getDepth();
1255 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1256 parser.getDepth() > groupDepth) {
1257 if (type != XmlPullParser.START_TAG) {
1258 continue;
1259 }
1260 final String fallback_item_name = parser.getName();
1261 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1262 R.styleable.Favorite);
1263 if (!added) {
1264 if (TAG_FAVORITE.equals(fallback_item_name)) {
1265 final long id =
1266 addAppShortcut(db, values, ar, packageManager, intent);
1267 added = id >= 0;
1268 } else {
1269 Log.e(TAG, "Fallback groups can contain only favorites "
1270 + ar.toString());
1271 }
1272 }
1273 ar.recycle();
1274 }
Winson Chung6d092682011-11-16 18:43:26 -08001275 } else if (TAG_FOLDER.equals(name)) {
1276 String title;
1277 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1278 if (titleResId != -1) {
1279 title = mContext.getResources().getString(titleResId);
1280 } else {
1281 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001282 }
Winson Chung6d092682011-11-16 18:43:26 -08001283 values.put(LauncherSettings.Favorites.TITLE, title);
1284 long folderId = addFolder(db, values);
1285 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001286
Winson Chung6d092682011-11-16 18:43:26 -08001287 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001288
Winson Chung6d092682011-11-16 18:43:26 -08001289 int folderDepth = parser.getDepth();
1290 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1291 parser.getDepth() > folderDepth) {
1292 if (type != XmlPullParser.START_TAG) {
1293 continue;
1294 }
1295 final String folder_item_name = parser.getName();
1296
1297 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1298 R.styleable.Favorite);
1299 values.clear();
1300 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1301
Daniel Sandler57dac262013-10-03 13:28:36 -04001302 if (LOGD) {
1303 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1304 final String uri = ar.getString(R.styleable.Favorite_uri);
1305 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1306 folder_item_name, uri != null ? uri : pkg));
1307 }
1308
Winson Chung6d092682011-11-16 18:43:26 -08001309 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1310 long id =
1311 addAppShortcut(db, values, ar, packageManager, intent);
1312 if (id >= 0) {
1313 folderItems.add(id);
1314 }
1315 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1316 long id = addUriShortcut(db, values, ar);
1317 if (id >= 0) {
1318 folderItems.add(id);
1319 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001320 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001321 throw new RuntimeException("Folders can " +
1322 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001323 }
Winson Chung6d092682011-11-16 18:43:26 -08001324 ar.recycle();
1325 }
1326 // We can only have folders with >= 2 items, so we need to remove the
1327 // folder and clean up if less than 2 items were included, or some
1328 // failed to add, and less than 2 were actually added
1329 if (folderItems.size() < 2 && folderId >= 0) {
1330 // We just delete the folder and any items that made it
1331 deleteId(db, folderId);
1332 if (folderItems.size() > 0) {
1333 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001334 }
Winson Chung6d092682011-11-16 18:43:26 -08001335 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001336 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001337 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001338 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001339 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001340 }
1341 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001342 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001343 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001344 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001345 } catch (RuntimeException e) {
1346 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001347 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001348
Winson Chungc763c4e2013-07-19 13:49:06 -07001349 // Update the max item id after we have loaded the database
1350 if (mMaxItemId == -1) {
1351 mMaxItemId = initializeMaxItemId(db);
1352 }
1353
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001354 return i;
1355 }
1356
Jason Monk41314972014-03-03 16:11:30 -05001357 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1358 // logical choice for what shortcut should be used for that intent exists, then it is
1359 // added. Otherwise add nothing.
1360 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001361 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001362 final String intentUri = a.getString(R.styleable.Favorite_uri);
1363
1364 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001365 try {
Jason Monk41314972014-03-03 16:11:30 -05001366 metaIntent = Intent.parseUri(intentUri, 0);
1367 } catch (URISyntaxException e) {
1368 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1369 return -1;
1370 }
1371
1372 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1373 PackageManager.MATCH_DEFAULT_ONLY);
1374 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1375 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1376
1377 // Verify that the result is an app and not just the resolver dialog asking which
1378 // app to use.
1379 if (wouldLaunchResolverActivity(resolved, appList)) {
1380 // If only one of the results is a system app then choose that as the default.
1381 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1382 if (systemApp == null) {
1383 // There is no logical choice for this meta-favorite, so rather than making
1384 // a bad choice just add nothing.
1385 Log.w(TAG, "No preference or single system activity found for "
1386 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001387 return -1;
1388 }
Jason Monk41314972014-03-03 16:11:30 -05001389 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001390 }
Jason Monk41314972014-03-03 16:11:30 -05001391 final ActivityInfo info = resolved.activityInfo;
1392 intent.setComponent(new ComponentName(info.packageName, info.name));
1393 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1394 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1395
1396 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1397 }
1398
1399 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1400 PackageManager packageManager) {
1401 ResolveInfo systemResolve = null;
1402 final int N = appList.size();
1403 for (int i = 0; i < N; ++i) {
1404 try {
1405 ApplicationInfo info = packageManager.getApplicationInfo(
1406 appList.get(i).activityInfo.packageName, 0);
1407 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1408 if (systemResolve != null) {
1409 return null;
1410 } else {
1411 systemResolve = appList.get(i);
1412 }
1413 }
1414 } catch (PackageManager.NameNotFoundException e) {
1415 Log.w(TAG, "Unable to get info about resolve results", e);
1416 return null;
1417 }
1418 }
1419 return systemResolve;
1420 }
1421
1422 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1423 List<ResolveInfo> appList) {
1424 // If the list contains the above resolved activity, then it can't be
1425 // ResolverActivity itself.
1426 for (int i = 0; i < appList.size(); ++i) {
1427 ResolveInfo tmp = appList.get(i);
1428 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1429 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1430 return false;
1431 }
1432 }
1433 return true;
1434 }
1435
1436 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1437 PackageManager packageManager, Intent intent) {
1438 if (a.hasValue(R.styleable.Favorite_packageName)
1439 && a.hasValue(R.styleable.Favorite_className)) {
1440 ActivityInfo info;
1441 String packageName = a.getString(R.styleable.Favorite_packageName);
1442 String className = a.getString(R.styleable.Favorite_className);
1443 try {
1444 ComponentName cn;
1445 try {
1446 cn = new ComponentName(packageName, className);
1447 info = packageManager.getActivityInfo(cn, 0);
1448 } catch (PackageManager.NameNotFoundException nnfe) {
1449 String[] packages = packageManager.currentToCanonicalPackageNames(
1450 new String[] { packageName });
1451 cn = new ComponentName(packages[0], className);
1452 info = packageManager.getActivityInfo(cn, 0);
1453 }
1454 intent.setComponent(cn);
1455 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1456 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1457
1458 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1459 intent);
1460 } catch (PackageManager.NameNotFoundException e) {
1461 Log.w(TAG, "Unable to add favorite: " + packageName +
1462 "/" + className, e);
1463 }
1464 return -1;
1465 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1466 // If no component specified try to find a shortcut to add from the URI.
1467 return addAppShortcutByUri(db, values, a, packageManager, intent);
1468 } else {
1469 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1470 return -1;
1471 }
1472 }
1473
1474 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1475 Intent intent) {
1476 long id = generateNewItemId();
1477 values.put(Favorites.INTENT, intent.toUri(0));
1478 values.put(Favorites.TITLE, title);
1479 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1480 values.put(Favorites.SPANX, 1);
1481 values.put(Favorites.SPANY, 1);
1482 values.put(Favorites._ID, id);
1483 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1484 return -1;
1485 } else {
1486 return id;
1487 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001488 }
1489
1490 private long addFolder(SQLiteDatabase db, ContentValues values) {
1491 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1492 values.put(Favorites.SPANX, 1);
1493 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001494 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001495 values.put(Favorites._ID, id);
1496 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1497 return -1;
1498 } else {
1499 return id;
1500 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001501 }
1502
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001503 private ComponentName getSearchWidgetProvider() {
1504 SearchManager searchManager =
1505 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1506 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1507 if (searchComponent == null) return null;
1508 return getProviderInPackage(searchComponent.getPackageName());
1509 }
1510
1511 /**
1512 * Gets an appwidget provider from the given package. If the package contains more than
1513 * one appwidget provider, an arbitrary one is returned.
1514 */
1515 private ComponentName getProviderInPackage(String packageName) {
1516 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1517 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1518 if (providers == null) return null;
1519 final int providerCount = providers.size();
1520 for (int i = 0; i < providerCount; i++) {
1521 ComponentName provider = providers.get(i).provider;
1522 if (provider != null && provider.getPackageName().equals(packageName)) {
1523 return provider;
1524 }
1525 }
1526 return null;
1527 }
1528
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001529 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001530 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001531 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001532 }
1533
1534 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001535 ComponentName cn = new ComponentName("com.android.alarmclock",
1536 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001537 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001538 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001539
Winson Chungb3302ae2012-05-01 10:19:14 -07001540 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1541 SQLiteDatabase db, ContentValues values, TypedArray a,
1542 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001543
Mike Cleronb87bd162009-10-30 16:36:56 -07001544 String packageName = a.getString(R.styleable.Favorite_packageName);
1545 String className = a.getString(R.styleable.Favorite_className);
1546
1547 if (packageName == null || className == null) {
1548 return false;
1549 }
Romain Guy693599f2010-03-23 10:58:18 -07001550
1551 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001552 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001553 try {
1554 packageManager.getReceiverInfo(cn, 0);
1555 } catch (Exception e) {
1556 String[] packages = packageManager.currentToCanonicalPackageNames(
1557 new String[] { packageName });
1558 cn = new ComponentName(packages[0], className);
1559 try {
1560 packageManager.getReceiverInfo(cn, 0);
1561 } catch (Exception e1) {
1562 hasPackage = false;
1563 }
1564 }
1565
1566 if (hasPackage) {
1567 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1568 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001569
1570 // Read the extras
1571 Bundle extras = new Bundle();
1572 int widgetDepth = parser.getDepth();
1573 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1574 parser.getDepth() > widgetDepth) {
1575 if (type != XmlPullParser.START_TAG) {
1576 continue;
1577 }
1578
1579 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1580 if (TAG_EXTRA.equals(parser.getName())) {
1581 String key = ar.getString(R.styleable.Extra_key);
1582 String value = ar.getString(R.styleable.Extra_value);
1583 if (key != null && value != null) {
1584 extras.putString(key, value);
1585 } else {
1586 throw new RuntimeException("Widget extras must have a key and value");
1587 }
1588 } else {
1589 throw new RuntimeException("Widgets can contain only extras");
1590 }
1591 ar.recycle();
1592 }
1593
1594 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001595 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001596
Romain Guy693599f2010-03-23 10:58:18 -07001597 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001598 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001599 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001600 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001601 boolean allocatedAppWidgets = false;
1602 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1603
1604 try {
1605 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001606
Mike Cleronb87bd162009-10-30 16:36:56 -07001607 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001608 values.put(Favorites.SPANX, spanX);
1609 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001610 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001611 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001612 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001613 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001614
1615 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001616
Michael Jurka8b805b12012-04-18 14:23:14 -07001617 // TODO: need to check return value
1618 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001619
1620 // Send a broadcast to configure the widget
1621 if (extras != null && !extras.isEmpty()) {
1622 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1623 intent.setComponent(cn);
1624 intent.putExtras(extras);
1625 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1626 mContext.sendBroadcast(intent);
1627 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001628 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001629 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001630 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001631
Mike Cleronb87bd162009-10-30 16:36:56 -07001632 return allocatedAppWidgets;
1633 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001634
1635 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001636 TypedArray a) {
1637 Resources r = mContext.getResources();
1638
1639 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1640 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1641
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001642 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001643 String uri = null;
1644 try {
1645 uri = a.getString(R.styleable.Favorite_uri);
1646 intent = Intent.parseUri(uri, 0);
1647 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001648 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001649 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001650 }
1651
1652 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001653 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001654 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001655 }
1656
Adam Cohendcd297f2013-06-18 13:13:40 -07001657 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001658 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1659 values.put(Favorites.INTENT, intent.toUri(0));
1660 values.put(Favorites.TITLE, r.getString(titleResId));
1661 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1662 values.put(Favorites.SPANX, 1);
1663 values.put(Favorites.SPANY, 1);
1664 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1665 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1666 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001667 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001668
Adam Cohen228da5a2011-07-27 22:23:47 -07001669 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1670 return -1;
1671 }
1672 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001673 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001674
1675 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1676 final ContentResolver resolver = mContext.getContentResolver();
1677 Cursor c = null;
1678 int count = 0;
1679 int curScreen = 0;
1680
1681 try {
1682 c = resolver.query(uri, null, null, null, "title ASC");
1683 } catch (Exception e) {
1684 // Ignore
1685 }
1686
Dan Sandlerd5024042014-01-09 15:01:33 -05001687 // We already have a favorites database in the old provider
1688 if (c != null) {
1689 try {
1690 if (c.getCount() > 0) {
1691 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1692 final int intentIndex
1693 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1694 final int titleIndex
1695 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1696 final int iconTypeIndex
1697 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1698 final int iconIndex
1699 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1700 final int iconPackageIndex
1701 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1702 final int iconResourceIndex
1703 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1704 final int containerIndex
1705 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1706 final int itemTypeIndex
1707 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1708 final int screenIndex
1709 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1710 final int cellXIndex
1711 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1712 final int cellYIndex
1713 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1714 final int uriIndex
1715 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1716 final int displayModeIndex
1717 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1718
1719 int i = 0;
1720 int curX = 0;
1721 int curY = 0;
1722
1723 final LauncherAppState app = LauncherAppState.getInstance();
1724 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1725 final int width = (int) grid.numColumns;
1726 final int height = (int) grid.numRows;
1727 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001728 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001729
1730 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1731
Adam Cohen72960972014-01-15 18:13:55 -08001732 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1733 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001734 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001735
1736 while (c.moveToNext()) {
1737 final int itemType = c.getInt(itemTypeIndex);
1738 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1739 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1740 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1741 continue;
1742 }
1743
1744 final int cellX = c.getInt(cellXIndex);
1745 final int cellY = c.getInt(cellYIndex);
1746 final int screen = c.getInt(screenIndex);
1747 int container = c.getInt(containerIndex);
1748 final String intentStr = c.getString(intentIndex);
1749 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001750 + c.getString(titleIndex) + "\" ("
1751 + cellX + "," + cellY + "@"
1752 + LauncherSettings.Favorites.containerToString(container)
1753 + "/" + screen
1754 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001755
1756 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001757
1758 final Intent intent;
1759 final ComponentName cn;
1760 try {
1761 intent = Intent.parseUri(intentStr, 0);
1762 } catch (URISyntaxException e) {
1763 // bogus intent?
1764 Launcher.addDumpLog(TAG,
1765 "skipping invalid intent uri", true);
1766 continue;
1767 }
1768
1769 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001770 if (TextUtils.isEmpty(intentStr)) {
1771 // no intent? no icon
1772 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1773 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001774 } else if (cn != null &&
1775 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001776 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001777 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001778 "no longer exists.", true);
1779 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001780 } else if (container ==
1781 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1782 // Dedupe icons directly on the workspace
1783
Adam Cohen556f6132014-01-15 15:18:08 -08001784 // Canonicalize
1785 // the Play Store sets the package parameter, but Launcher
1786 // does not, so we clear that out to keep them the same
1787 intent.setPackage(null);
1788 final String key = intent.toUri(0);
1789 if (seenIntents.contains(key)) {
1790 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001791 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001792 } else {
1793 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001794 }
1795 }
1796 }
1797
1798 ContentValues values = new ContentValues(c.getColumnCount());
1799 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1800 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1801 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1802 values.put(LauncherSettings.Favorites.ICON_TYPE,
1803 c.getInt(iconTypeIndex));
1804 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1805 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1806 c.getString(iconPackageIndex));
1807 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1808 c.getString(iconResourceIndex));
1809 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1810 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1811 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1812 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1813 c.getInt(displayModeIndex));
1814
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001815 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1816 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001817 }
1818
1819 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1820 // In a folder or in the hotseat, preserve position
1821 values.put(LauncherSettings.Favorites.SCREEN, screen);
1822 values.put(LauncherSettings.Favorites.CELLX, cellX);
1823 values.put(LauncherSettings.Favorites.CELLY, cellY);
1824 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001825 // For items contained directly on one of the workspace screen,
1826 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001827 }
1828
1829 values.put(LauncherSettings.Favorites.CONTAINER, container);
1830
Adam Cohen72960972014-01-15 18:13:55 -08001831 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1832 shortcuts.add(values);
1833 } else {
1834 folders.add(values);
1835 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001836 }
1837
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001838 // Now that we have all the hotseat icons, let's go through them left-right
1839 // and assign valid locations for them in the new hotseat
1840 final int N = hotseat.size();
1841 for (int idx=0; idx<N; idx++) {
1842 int hotseatX = hotseat.keyAt(idx);
1843 ContentValues values = hotseat.valueAt(idx);
1844
1845 if (hotseatX == grid.hotseatAllAppsRank) {
1846 // let's drop this in the next available hole in the hotseat
1847 while (++hotseatX < hotseatWidth) {
1848 if (hotseat.get(hotseatX) == null) {
1849 // found a spot! move it here
1850 values.put(LauncherSettings.Favorites.SCREEN,
1851 hotseatX);
1852 break;
1853 }
1854 }
1855 }
1856 if (hotseatX >= hotseatWidth) {
1857 // no room for you in the hotseat? it's off to the desktop with you
1858 values.put(LauncherSettings.Favorites.CONTAINER,
1859 Favorites.CONTAINER_DESKTOP);
1860 }
1861 }
1862
Adam Cohen72960972014-01-15 18:13:55 -08001863 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1864 // Folders first
1865 allItems.addAll(folders);
1866 // Then shortcuts
1867 allItems.addAll(shortcuts);
1868
1869 // Layout all the folders
1870 for (ContentValues values: allItems) {
1871 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1872 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1873 // Hotseat items and folder items have already had their
1874 // location information set. Nothing to be done here.
1875 continue;
1876 }
1877 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1878 values.put(LauncherSettings.Favorites.CELLX, curX);
1879 values.put(LauncherSettings.Favorites.CELLY, curY);
1880 curX = (curX + 1) % width;
1881 if (curX == 0) {
1882 curY = (curY + 1);
1883 }
1884 // Leave the last row of icons blank on every screen
1885 if (curY == height - 1) {
1886 curScreen = (int) generateNewScreenId();
1887 curY = 0;
1888 }
1889 }
1890
1891 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001892 db.beginTransaction();
1893 try {
Adam Cohen72960972014-01-15 18:13:55 -08001894 for (ContentValues row: allItems) {
1895 if (row == null) continue;
1896 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001897 < 0) {
1898 return;
1899 } else {
1900 count++;
1901 }
1902 }
1903 db.setTransactionSuccessful();
1904 } finally {
1905 db.endTransaction();
1906 }
1907 }
1908
1909 db.beginTransaction();
1910 try {
1911 for (i=0; i<=curScreen; i++) {
1912 final ContentValues values = new ContentValues();
1913 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1914 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1915 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1916 < 0) {
1917 return;
1918 }
1919 }
1920 db.setTransactionSuccessful();
1921 } finally {
1922 db.endTransaction();
1923 }
1924 }
1925 } finally {
1926 c.close();
1927 }
1928 }
1929
1930 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1931 + (curScreen+1) + " screens", true);
1932
1933 // ensure that new screens are created to hold these icons
1934 setFlagJustLoadedOldDb();
1935
1936 // Update max IDs; very important since we just grabbed IDs from another database
1937 mMaxItemId = initializeMaxItemId(db);
1938 mMaxScreenId = initializeMaxScreenId(db);
1939 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1940 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001941 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001942
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001943 /**
1944 * Build a query string that will match any row where the column matches
1945 * anything in the values list.
1946 */
1947 static String buildOrWhereString(String column, int[] values) {
1948 StringBuilder selectWhere = new StringBuilder();
1949 for (int i = values.length - 1; i >= 0; i--) {
1950 selectWhere.append(column).append("=").append(values[i]);
1951 if (i > 0) {
1952 selectWhere.append(" OR ");
1953 }
1954 }
1955 return selectWhere.toString();
1956 }
1957
1958 static class SqlArguments {
1959 public final String table;
1960 public final String where;
1961 public final String[] args;
1962
1963 SqlArguments(Uri url, String where, String[] args) {
1964 if (url.getPathSegments().size() == 1) {
1965 this.table = url.getPathSegments().get(0);
1966 this.where = where;
1967 this.args = args;
1968 } else if (url.getPathSegments().size() != 2) {
1969 throw new IllegalArgumentException("Invalid URI: " + url);
1970 } else if (!TextUtils.isEmpty(where)) {
1971 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1972 } else {
1973 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001974 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001975 this.args = null;
1976 }
1977 }
1978
1979 SqlArguments(Uri url) {
1980 if (url.getPathSegments().size() == 1) {
1981 table = url.getPathSegments().get(0);
1982 where = null;
1983 args = null;
1984 } else {
1985 throw new IllegalArgumentException("Invalid URI: " + url);
1986 }
1987 }
1988 }
Adam Cohen72960972014-01-15 18:13:55 -08001989}