blob: fa3a75299a20ae94334cd307072e55bc678eb2e1 [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.
807 removeOrphanedItems(db);
808 version = 18;
809 }
810
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800811 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800812 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800813 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
815
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800816 onCreate(db);
817 }
818 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800819
820 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800821 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
822 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
823
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700824 Cursor c = null;
825 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800826 db.beginTransaction();
827 try {
828 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700829 c = db.query(TABLE_FAVORITES,
830 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800831 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700832 if (c == null) return false;
833
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800834 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700835
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800836 final int idIndex = c.getColumnIndex(Favorites._ID);
837 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700838
839 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800840 long favoriteId = c.getLong(idIndex);
841 final String intentUri = c.getString(intentIndex);
842 if (intentUri != null) {
843 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700844 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800845 android.util.Log.d("Home", intent.toString());
846 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700847 if (uri != null) {
848 final String data = uri.toString();
849 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
850 actionQuickContact.equals(intent.getAction())) &&
851 (data.startsWith("content://contacts/people/") ||
852 data.startsWith("content://com.android.contacts/" +
853 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800854
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700855 final Intent newIntent = new Intent(actionQuickContact);
856 // When starting from the launcher, start in a new, cleared task
857 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
858 // clear the whole thing preemptively here since
859 // QuickContactActivity will finish itself when launching other
860 // detail activities.
861 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
862 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700863 newIntent.putExtra(
864 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700865 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700866 // Determine the type and also put that in the shortcut
867 // (that can speed up launch a bit)
868 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800869
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700870 final ContentValues values = new ContentValues();
871 values.put(LauncherSettings.Favorites.INTENT,
872 newIntent.toUri(0));
873
874 String updateWhere = Favorites._ID + "=" + favoriteId;
875 db.update(TABLE_FAVORITES, values, updateWhere, null);
876 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800877 }
878 } catch (RuntimeException ex) {
879 Log.e(TAG, "Problem upgrading shortcut", ex);
880 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700881 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800882 }
883 }
884 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700885
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800886 db.setTransactionSuccessful();
887 } catch (SQLException ex) {
888 Log.w(TAG, "Problem while upgrading contacts", ex);
889 return false;
890 } finally {
891 db.endTransaction();
892 if (c != null) {
893 c.close();
894 }
895 }
896
897 return true;
898 }
899
Joe Onorato0589f0f2010-02-08 13:44:00 -0800900 private void normalizeIcons(SQLiteDatabase db) {
901 Log.d(TAG, "normalizing icons");
902
Joe Onorato346e1292010-02-18 10:34:24 -0500903 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800904 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400905 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800906 try {
907 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400908 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600909 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800910
911 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
912 Favorites.ICON_TYPE_BITMAP, null);
913
914 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
915 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
916
917 while (c.moveToNext()) {
918 long id = c.getLong(idIndex);
919 byte[] data = c.getBlob(iconIndex);
920 try {
921 Bitmap bitmap = Utilities.resampleIconBitmap(
922 BitmapFactory.decodeByteArray(data, 0, data.length),
923 mContext);
924 if (bitmap != null) {
925 update.bindLong(1, id);
926 data = ItemInfo.flattenBitmap(bitmap);
927 if (data != null) {
928 update.bindBlob(2, data);
929 update.execute();
930 }
931 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800932 }
933 } catch (Exception e) {
934 if (!logged) {
935 Log.e(TAG, "Failed normalizing icon " + id, e);
936 } else {
937 Log.e(TAG, "Also failed normalizing icon " + id);
938 }
939 logged = true;
940 }
941 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000942 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800943 } catch (SQLException ex) {
944 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
945 } finally {
946 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400947 if (update != null) {
948 update.close();
949 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800950 if (c != null) {
951 c.close();
952 }
953 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700954 }
955
956 // Generates a new ID to use for an object in your database. This method should be only
957 // called from the main UI thread. As an exception, we do call it when we call the
958 // constructor from the worker thread; however, this doesn't extend until after the
959 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
960 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700961 public long generateNewItemId() {
962 if (mMaxItemId < 0) {
963 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700964 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700965 mMaxItemId += 1;
966 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700967 }
968
Winson Chungc763c4e2013-07-19 13:49:06 -0700969 public void updateMaxItemId(long id) {
970 mMaxItemId = id + 1;
971 }
972
Chris Wren5dee7af2013-12-20 17:22:11 -0500973 public void checkId(String table, ContentValues values) {
974 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
975 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
976 mMaxScreenId = Math.max(id, mMaxScreenId);
977 } else {
978 mMaxItemId = Math.max(id, mMaxItemId);
979 }
980 }
981
Adam Cohendcd297f2013-06-18 13:13:40 -0700982 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700983 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
984
985 // get the result
986 final int maxIdIndex = 0;
987 long id = -1;
988 if (c != null && c.moveToNext()) {
989 id = c.getLong(maxIdIndex);
990 }
Michael Jurka5130e402011-10-13 04:55:35 -0700991 if (c != null) {
992 c.close();
993 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700994
995 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 throw new RuntimeException("Error: could not query max item id");
997 }
998
999 return id;
1000 }
1001
1002 // Generates a new ID to use for an workspace screen in your database. This method
1003 // should be only called from the main UI thread. As an exception, we do call it when we
1004 // call the constructor from the worker thread; however, this doesn't extend until after the
1005 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1006 // after that point
1007 public long generateNewScreenId() {
1008 if (mMaxScreenId < 0) {
1009 throw new RuntimeException("Error: max screen id was not initialized");
1010 }
1011 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001012 // Log to disk
1013 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001014 return mMaxScreenId;
1015 }
1016
1017 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001018 // Log to disk
1019 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 mMaxScreenId = maxScreenId;
1021 }
1022
1023 private long initializeMaxScreenId(SQLiteDatabase db) {
1024 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1025
1026 // get the result
1027 final int maxIdIndex = 0;
1028 long id = -1;
1029 if (c != null && c.moveToNext()) {
1030 id = c.getLong(maxIdIndex);
1031 }
1032 if (c != null) {
1033 c.close();
1034 }
1035
1036 if (id == -1) {
1037 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001038 }
1039
Winson Chunga90303b2013-11-15 13:05:06 -08001040 // Log to disk
1041 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001042 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001043 }
1044
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001045 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001046 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001047 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001048 */
1049 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001050 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001051 final int[] bindSources = new int[] {
1052 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1053 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001054 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001055 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001056
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001057 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001058
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001059 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001060
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001061 db.beginTransaction();
1062 try {
1063 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001064 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001065 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001066
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001067 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001068
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001069 final ContentValues values = new ContentValues();
1070 while (c != null && c.moveToNext()) {
1071 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001072 int favoriteType = c.getInt(1);
1073
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001074 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001075 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001076 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001077
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001078 if (LOGD) {
1079 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1080 + " for favoriteId=" + favoriteId);
1081 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001082 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001083 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1084 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1085
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001086 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001087 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1088 values.put(LauncherSettings.Favorites.SPANX, 4);
1089 values.put(LauncherSettings.Favorites.SPANY, 1);
1090 } else {
1091 values.put(LauncherSettings.Favorites.SPANX, 2);
1092 values.put(LauncherSettings.Favorites.SPANY, 2);
1093 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001094
1095 String updateWhere = Favorites._ID + "=" + favoriteId;
1096 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001097
Bjorn Bringert34251342009-12-15 13:33:11 +00001098 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001099 // TODO: check return value
1100 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001101 new ComponentName("com.android.alarmclock",
1102 "com.android.alarmclock.AnalogAppWidgetProvider"));
1103 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001104 // TODO: check return value
1105 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001106 new ComponentName("com.android.camera",
1107 "com.android.camera.PhotoAppWidgetProvider"));
1108 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001109 // TODO: check return value
1110 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001111 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001112 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001113 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001114 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001115 }
1116 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001117
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001118 db.setTransactionSuccessful();
1119 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001120 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001121 } finally {
1122 db.endTransaction();
1123 if (c != null) {
1124 c.close();
1125 }
1126 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001127
1128 // Update max item id
1129 mMaxItemId = initializeMaxItemId(db);
1130 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001131 }
1132
Michael Jurka8b805b12012-04-18 14:23:14 -07001133 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1134 throws XmlPullParserException, IOException {
1135 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001136 while ((type = parser.next()) != XmlPullParser.START_TAG
1137 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001138 ;
1139 }
1140
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001141 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001142 throw new XmlPullParserException("No start tag found");
1143 }
1144
1145 if (!parser.getName().equals(firstElementName)) {
1146 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1147 ", expected " + firstElementName);
1148 }
1149 }
1150
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001151 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001152 * Loads the default set of favorite packages from an xml file.
1153 *
1154 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001155 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001156 */
Winson Chung6d092682011-11-16 18:43:26 -08001157 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001158 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1159 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1160 ContentValues values = new ContentValues();
1161
Daniel Sandler57dac262013-10-03 13:28:36 -04001162 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1163
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001164 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001165 int i = 0;
1166 try {
Winson Chung6d092682011-11-16 18:43:26 -08001167 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001168 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001169 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001170
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001171 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001172
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001173 int type;
1174 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1175 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1176
1177 if (type != XmlPullParser.START_TAG) {
1178 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001179 }
1180
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001181 boolean added = false;
1182 final String name = parser.getName();
1183
Daniel Sandler57dac262013-10-03 13:28:36 -04001184 if (TAG_INCLUDE.equals(name)) {
1185 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1186
1187 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1188
1189 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1190 "", resId));
1191
1192 if (resId != 0 && resId != workspaceResourceId) {
1193 // recursively load some more favorites, why not?
1194 i += loadFavorites(db, resId);
1195 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001196 } else {
1197 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1198 }
1199
1200 a.recycle();
1201
1202 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1203 continue;
1204 }
1205
1206 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001207 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1208
Winson Chung3d503fb2011-07-13 17:25:49 -07001209 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1210 if (a.hasValue(R.styleable.Favorite_container)) {
1211 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1212 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001213
Winson Chung6d092682011-11-16 18:43:26 -08001214 String screen = a.getString(R.styleable.Favorite_screen);
1215 String x = a.getString(R.styleable.Favorite_x);
1216 String y = a.getString(R.styleable.Favorite_y);
1217
Winson Chung6d092682011-11-16 18:43:26 -08001218 values.clear();
1219 values.put(LauncherSettings.Favorites.CONTAINER, container);
1220 values.put(LauncherSettings.Favorites.SCREEN, screen);
1221 values.put(LauncherSettings.Favorites.CELLX, x);
1222 values.put(LauncherSettings.Favorites.CELLY, y);
1223
Daniel Sandler57dac262013-10-03 13:28:36 -04001224 if (LOGD) {
1225 final String title = a.getString(R.styleable.Favorite_title);
1226 final String pkg = a.getString(R.styleable.Favorite_packageName);
1227 final String something = title != null ? title : pkg;
1228 Log.v(TAG, String.format(
1229 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1230 "", name,
1231 (something == null ? "" : (" \"" + something + "\"")),
1232 container, screen, x, y));
1233 }
1234
Winson Chung6d092682011-11-16 18:43:26 -08001235 if (TAG_FAVORITE.equals(name)) {
1236 long id = addAppShortcut(db, values, a, packageManager, intent);
1237 added = id >= 0;
1238 } else if (TAG_SEARCH.equals(name)) {
1239 added = addSearchWidget(db, values);
1240 } else if (TAG_CLOCK.equals(name)) {
1241 added = addClockWidget(db, values);
1242 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001243 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001244 } else if (TAG_SHORTCUT.equals(name)) {
1245 long id = addUriShortcut(db, values, a);
1246 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001247 } else if (TAG_RESOLVE.equals(name)) {
1248 // This looks through the contained favorites (or meta-favorites) and
1249 // attempts to add them as shortcuts in the fallback group's location
1250 // until one is added successfully.
1251 added = false;
1252 final int groupDepth = parser.getDepth();
1253 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1254 parser.getDepth() > groupDepth) {
1255 if (type != XmlPullParser.START_TAG) {
1256 continue;
1257 }
1258 final String fallback_item_name = parser.getName();
1259 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1260 R.styleable.Favorite);
1261 if (!added) {
1262 if (TAG_FAVORITE.equals(fallback_item_name)) {
1263 final long id =
1264 addAppShortcut(db, values, ar, packageManager, intent);
1265 added = id >= 0;
1266 } else {
1267 Log.e(TAG, "Fallback groups can contain only favorites "
1268 + ar.toString());
1269 }
1270 }
1271 ar.recycle();
1272 }
Winson Chung6d092682011-11-16 18:43:26 -08001273 } else if (TAG_FOLDER.equals(name)) {
1274 String title;
1275 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1276 if (titleResId != -1) {
1277 title = mContext.getResources().getString(titleResId);
1278 } else {
1279 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001280 }
Winson Chung6d092682011-11-16 18:43:26 -08001281 values.put(LauncherSettings.Favorites.TITLE, title);
1282 long folderId = addFolder(db, values);
1283 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001284
Winson Chung6d092682011-11-16 18:43:26 -08001285 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001286
Winson Chung6d092682011-11-16 18:43:26 -08001287 int folderDepth = parser.getDepth();
1288 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1289 parser.getDepth() > folderDepth) {
1290 if (type != XmlPullParser.START_TAG) {
1291 continue;
1292 }
1293 final String folder_item_name = parser.getName();
1294
1295 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1296 R.styleable.Favorite);
1297 values.clear();
1298 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1299
Daniel Sandler57dac262013-10-03 13:28:36 -04001300 if (LOGD) {
1301 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1302 final String uri = ar.getString(R.styleable.Favorite_uri);
1303 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1304 folder_item_name, uri != null ? uri : pkg));
1305 }
1306
Winson Chung6d092682011-11-16 18:43:26 -08001307 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1308 long id =
1309 addAppShortcut(db, values, ar, packageManager, intent);
1310 if (id >= 0) {
1311 folderItems.add(id);
1312 }
1313 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1314 long id = addUriShortcut(db, values, ar);
1315 if (id >= 0) {
1316 folderItems.add(id);
1317 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001318 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001319 throw new RuntimeException("Folders can " +
1320 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001321 }
Winson Chung6d092682011-11-16 18:43:26 -08001322 ar.recycle();
1323 }
1324 // We can only have folders with >= 2 items, so we need to remove the
1325 // folder and clean up if less than 2 items were included, or some
1326 // failed to add, and less than 2 were actually added
1327 if (folderItems.size() < 2 && folderId >= 0) {
1328 // We just delete the folder and any items that made it
1329 deleteId(db, folderId);
1330 if (folderItems.size() > 0) {
1331 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001332 }
Winson Chung6d092682011-11-16 18:43:26 -08001333 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001334 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001335 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001336 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001337 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001338 }
1339 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001340 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001341 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001342 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001343 } catch (RuntimeException e) {
1344 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001345 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001346
Winson Chungc763c4e2013-07-19 13:49:06 -07001347 // Update the max item id after we have loaded the database
1348 if (mMaxItemId == -1) {
1349 mMaxItemId = initializeMaxItemId(db);
1350 }
1351
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001352 return i;
1353 }
1354
Jason Monk41314972014-03-03 16:11:30 -05001355 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1356 // logical choice for what shortcut should be used for that intent exists, then it is
1357 // added. Otherwise add nothing.
1358 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001359 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001360 final String intentUri = a.getString(R.styleable.Favorite_uri);
1361
1362 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001363 try {
Jason Monk41314972014-03-03 16:11:30 -05001364 metaIntent = Intent.parseUri(intentUri, 0);
1365 } catch (URISyntaxException e) {
1366 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1367 return -1;
1368 }
1369
1370 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1371 PackageManager.MATCH_DEFAULT_ONLY);
1372 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1373 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1374
1375 // Verify that the result is an app and not just the resolver dialog asking which
1376 // app to use.
1377 if (wouldLaunchResolverActivity(resolved, appList)) {
1378 // If only one of the results is a system app then choose that as the default.
1379 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1380 if (systemApp == null) {
1381 // There is no logical choice for this meta-favorite, so rather than making
1382 // a bad choice just add nothing.
1383 Log.w(TAG, "No preference or single system activity found for "
1384 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001385 return -1;
1386 }
Jason Monk41314972014-03-03 16:11:30 -05001387 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001388 }
Jason Monk41314972014-03-03 16:11:30 -05001389 final ActivityInfo info = resolved.activityInfo;
1390 intent.setComponent(new ComponentName(info.packageName, info.name));
1391 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1392 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1393
1394 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1395 }
1396
1397 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1398 PackageManager packageManager) {
1399 ResolveInfo systemResolve = null;
1400 final int N = appList.size();
1401 for (int i = 0; i < N; ++i) {
1402 try {
1403 ApplicationInfo info = packageManager.getApplicationInfo(
1404 appList.get(i).activityInfo.packageName, 0);
1405 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1406 if (systemResolve != null) {
1407 return null;
1408 } else {
1409 systemResolve = appList.get(i);
1410 }
1411 }
1412 } catch (PackageManager.NameNotFoundException e) {
1413 Log.w(TAG, "Unable to get info about resolve results", e);
1414 return null;
1415 }
1416 }
1417 return systemResolve;
1418 }
1419
1420 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1421 List<ResolveInfo> appList) {
1422 // If the list contains the above resolved activity, then it can't be
1423 // ResolverActivity itself.
1424 for (int i = 0; i < appList.size(); ++i) {
1425 ResolveInfo tmp = appList.get(i);
1426 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1427 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1428 return false;
1429 }
1430 }
1431 return true;
1432 }
1433
1434 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1435 PackageManager packageManager, Intent intent) {
1436 if (a.hasValue(R.styleable.Favorite_packageName)
1437 && a.hasValue(R.styleable.Favorite_className)) {
1438 ActivityInfo info;
1439 String packageName = a.getString(R.styleable.Favorite_packageName);
1440 String className = a.getString(R.styleable.Favorite_className);
1441 try {
1442 ComponentName cn;
1443 try {
1444 cn = new ComponentName(packageName, className);
1445 info = packageManager.getActivityInfo(cn, 0);
1446 } catch (PackageManager.NameNotFoundException nnfe) {
1447 String[] packages = packageManager.currentToCanonicalPackageNames(
1448 new String[] { packageName });
1449 cn = new ComponentName(packages[0], className);
1450 info = packageManager.getActivityInfo(cn, 0);
1451 }
1452 intent.setComponent(cn);
1453 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1454 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1455
1456 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1457 intent);
1458 } catch (PackageManager.NameNotFoundException e) {
1459 Log.w(TAG, "Unable to add favorite: " + packageName +
1460 "/" + className, e);
1461 }
1462 return -1;
1463 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1464 // If no component specified try to find a shortcut to add from the URI.
1465 return addAppShortcutByUri(db, values, a, packageManager, intent);
1466 } else {
1467 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1468 return -1;
1469 }
1470 }
1471
1472 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1473 Intent intent) {
1474 long id = generateNewItemId();
1475 values.put(Favorites.INTENT, intent.toUri(0));
1476 values.put(Favorites.TITLE, title);
1477 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1478 values.put(Favorites.SPANX, 1);
1479 values.put(Favorites.SPANY, 1);
1480 values.put(Favorites._ID, id);
1481 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1482 return -1;
1483 } else {
1484 return id;
1485 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001486 }
1487
1488 private long addFolder(SQLiteDatabase db, ContentValues values) {
1489 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1490 values.put(Favorites.SPANX, 1);
1491 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001492 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001493 values.put(Favorites._ID, id);
1494 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1495 return -1;
1496 } else {
1497 return id;
1498 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001499 }
1500
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001501 private ComponentName getSearchWidgetProvider() {
1502 SearchManager searchManager =
1503 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1504 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1505 if (searchComponent == null) return null;
1506 return getProviderInPackage(searchComponent.getPackageName());
1507 }
1508
1509 /**
1510 * Gets an appwidget provider from the given package. If the package contains more than
1511 * one appwidget provider, an arbitrary one is returned.
1512 */
1513 private ComponentName getProviderInPackage(String packageName) {
1514 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1515 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1516 if (providers == null) return null;
1517 final int providerCount = providers.size();
1518 for (int i = 0; i < providerCount; i++) {
1519 ComponentName provider = providers.get(i).provider;
1520 if (provider != null && provider.getPackageName().equals(packageName)) {
1521 return provider;
1522 }
1523 }
1524 return null;
1525 }
1526
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001527 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001528 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001529 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001530 }
1531
1532 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001533 ComponentName cn = new ComponentName("com.android.alarmclock",
1534 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001535 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001536 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001537
Winson Chungb3302ae2012-05-01 10:19:14 -07001538 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1539 SQLiteDatabase db, ContentValues values, TypedArray a,
1540 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001541
Mike Cleronb87bd162009-10-30 16:36:56 -07001542 String packageName = a.getString(R.styleable.Favorite_packageName);
1543 String className = a.getString(R.styleable.Favorite_className);
1544
1545 if (packageName == null || className == null) {
1546 return false;
1547 }
Romain Guy693599f2010-03-23 10:58:18 -07001548
1549 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001550 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001551 try {
1552 packageManager.getReceiverInfo(cn, 0);
1553 } catch (Exception e) {
1554 String[] packages = packageManager.currentToCanonicalPackageNames(
1555 new String[] { packageName });
1556 cn = new ComponentName(packages[0], className);
1557 try {
1558 packageManager.getReceiverInfo(cn, 0);
1559 } catch (Exception e1) {
1560 hasPackage = false;
1561 }
1562 }
1563
1564 if (hasPackage) {
1565 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1566 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001567
1568 // Read the extras
1569 Bundle extras = new Bundle();
1570 int widgetDepth = parser.getDepth();
1571 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1572 parser.getDepth() > widgetDepth) {
1573 if (type != XmlPullParser.START_TAG) {
1574 continue;
1575 }
1576
1577 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1578 if (TAG_EXTRA.equals(parser.getName())) {
1579 String key = ar.getString(R.styleable.Extra_key);
1580 String value = ar.getString(R.styleable.Extra_value);
1581 if (key != null && value != null) {
1582 extras.putString(key, value);
1583 } else {
1584 throw new RuntimeException("Widget extras must have a key and value");
1585 }
1586 } else {
1587 throw new RuntimeException("Widgets can contain only extras");
1588 }
1589 ar.recycle();
1590 }
1591
1592 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001593 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001594
Romain Guy693599f2010-03-23 10:58:18 -07001595 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001596 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001597 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001598 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001599 boolean allocatedAppWidgets = false;
1600 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1601
1602 try {
1603 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001604
Mike Cleronb87bd162009-10-30 16:36:56 -07001605 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001606 values.put(Favorites.SPANX, spanX);
1607 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001608 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001609 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001610 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001611 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001612
1613 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001614
Michael Jurka8b805b12012-04-18 14:23:14 -07001615 // TODO: need to check return value
1616 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001617
1618 // Send a broadcast to configure the widget
1619 if (extras != null && !extras.isEmpty()) {
1620 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1621 intent.setComponent(cn);
1622 intent.putExtras(extras);
1623 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1624 mContext.sendBroadcast(intent);
1625 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001626 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001627 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001628 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001629
Mike Cleronb87bd162009-10-30 16:36:56 -07001630 return allocatedAppWidgets;
1631 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001632
1633 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001634 TypedArray a) {
1635 Resources r = mContext.getResources();
1636
1637 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1638 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1639
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001640 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001641 String uri = null;
1642 try {
1643 uri = a.getString(R.styleable.Favorite_uri);
1644 intent = Intent.parseUri(uri, 0);
1645 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001646 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001647 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001648 }
1649
1650 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001651 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001652 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001653 }
1654
Adam Cohendcd297f2013-06-18 13:13:40 -07001655 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001656 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1657 values.put(Favorites.INTENT, intent.toUri(0));
1658 values.put(Favorites.TITLE, r.getString(titleResId));
1659 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1660 values.put(Favorites.SPANX, 1);
1661 values.put(Favorites.SPANY, 1);
1662 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1663 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1664 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001665 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001666
Adam Cohen228da5a2011-07-27 22:23:47 -07001667 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1668 return -1;
1669 }
1670 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001671 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001672
1673 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1674 final ContentResolver resolver = mContext.getContentResolver();
1675 Cursor c = null;
1676 int count = 0;
1677 int curScreen = 0;
1678
1679 try {
1680 c = resolver.query(uri, null, null, null, "title ASC");
1681 } catch (Exception e) {
1682 // Ignore
1683 }
1684
Dan Sandlerd5024042014-01-09 15:01:33 -05001685 // We already have a favorites database in the old provider
1686 if (c != null) {
1687 try {
1688 if (c.getCount() > 0) {
1689 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1690 final int intentIndex
1691 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1692 final int titleIndex
1693 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1694 final int iconTypeIndex
1695 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1696 final int iconIndex
1697 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1698 final int iconPackageIndex
1699 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1700 final int iconResourceIndex
1701 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1702 final int containerIndex
1703 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1704 final int itemTypeIndex
1705 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1706 final int screenIndex
1707 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1708 final int cellXIndex
1709 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1710 final int cellYIndex
1711 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1712 final int uriIndex
1713 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1714 final int displayModeIndex
1715 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1716
1717 int i = 0;
1718 int curX = 0;
1719 int curY = 0;
1720
1721 final LauncherAppState app = LauncherAppState.getInstance();
1722 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1723 final int width = (int) grid.numColumns;
1724 final int height = (int) grid.numRows;
1725 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001726 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001727
1728 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1729
Adam Cohen72960972014-01-15 18:13:55 -08001730 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1731 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001732 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001733
1734 while (c.moveToNext()) {
1735 final int itemType = c.getInt(itemTypeIndex);
1736 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1737 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1738 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1739 continue;
1740 }
1741
1742 final int cellX = c.getInt(cellXIndex);
1743 final int cellY = c.getInt(cellYIndex);
1744 final int screen = c.getInt(screenIndex);
1745 int container = c.getInt(containerIndex);
1746 final String intentStr = c.getString(intentIndex);
1747 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001748 + c.getString(titleIndex) + "\" ("
1749 + cellX + "," + cellY + "@"
1750 + LauncherSettings.Favorites.containerToString(container)
1751 + "/" + screen
1752 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001753
1754 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001755
1756 final Intent intent;
1757 final ComponentName cn;
1758 try {
1759 intent = Intent.parseUri(intentStr, 0);
1760 } catch (URISyntaxException e) {
1761 // bogus intent?
1762 Launcher.addDumpLog(TAG,
1763 "skipping invalid intent uri", true);
1764 continue;
1765 }
1766
1767 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001768 if (TextUtils.isEmpty(intentStr)) {
1769 // no intent? no icon
1770 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1771 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001772 } else if (cn != null &&
1773 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001774 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001775 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001776 "no longer exists.", true);
1777 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001778 } else if (container ==
1779 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1780 // Dedupe icons directly on the workspace
1781
Adam Cohen556f6132014-01-15 15:18:08 -08001782 // Canonicalize
1783 // the Play Store sets the package parameter, but Launcher
1784 // does not, so we clear that out to keep them the same
1785 intent.setPackage(null);
1786 final String key = intent.toUri(0);
1787 if (seenIntents.contains(key)) {
1788 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001789 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001790 } else {
1791 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001792 }
1793 }
1794 }
1795
1796 ContentValues values = new ContentValues(c.getColumnCount());
1797 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1798 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1799 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1800 values.put(LauncherSettings.Favorites.ICON_TYPE,
1801 c.getInt(iconTypeIndex));
1802 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1803 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1804 c.getString(iconPackageIndex));
1805 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1806 c.getString(iconResourceIndex));
1807 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1808 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1809 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1810 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1811 c.getInt(displayModeIndex));
1812
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001813 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1814 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001815 }
1816
1817 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1818 // In a folder or in the hotseat, preserve position
1819 values.put(LauncherSettings.Favorites.SCREEN, screen);
1820 values.put(LauncherSettings.Favorites.CELLX, cellX);
1821 values.put(LauncherSettings.Favorites.CELLY, cellY);
1822 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001823 // For items contained directly on one of the workspace screen,
1824 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001825 }
1826
1827 values.put(LauncherSettings.Favorites.CONTAINER, container);
1828
Adam Cohen72960972014-01-15 18:13:55 -08001829 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1830 shortcuts.add(values);
1831 } else {
1832 folders.add(values);
1833 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001834 }
1835
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001836 // Now that we have all the hotseat icons, let's go through them left-right
1837 // and assign valid locations for them in the new hotseat
1838 final int N = hotseat.size();
1839 for (int idx=0; idx<N; idx++) {
1840 int hotseatX = hotseat.keyAt(idx);
1841 ContentValues values = hotseat.valueAt(idx);
1842
1843 if (hotseatX == grid.hotseatAllAppsRank) {
1844 // let's drop this in the next available hole in the hotseat
1845 while (++hotseatX < hotseatWidth) {
1846 if (hotseat.get(hotseatX) == null) {
1847 // found a spot! move it here
1848 values.put(LauncherSettings.Favorites.SCREEN,
1849 hotseatX);
1850 break;
1851 }
1852 }
1853 }
1854 if (hotseatX >= hotseatWidth) {
1855 // no room for you in the hotseat? it's off to the desktop with you
1856 values.put(LauncherSettings.Favorites.CONTAINER,
1857 Favorites.CONTAINER_DESKTOP);
1858 }
1859 }
1860
Adam Cohen72960972014-01-15 18:13:55 -08001861 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1862 // Folders first
1863 allItems.addAll(folders);
1864 // Then shortcuts
1865 allItems.addAll(shortcuts);
1866
1867 // Layout all the folders
1868 for (ContentValues values: allItems) {
1869 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1870 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1871 // Hotseat items and folder items have already had their
1872 // location information set. Nothing to be done here.
1873 continue;
1874 }
1875 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1876 values.put(LauncherSettings.Favorites.CELLX, curX);
1877 values.put(LauncherSettings.Favorites.CELLY, curY);
1878 curX = (curX + 1) % width;
1879 if (curX == 0) {
1880 curY = (curY + 1);
1881 }
1882 // Leave the last row of icons blank on every screen
1883 if (curY == height - 1) {
1884 curScreen = (int) generateNewScreenId();
1885 curY = 0;
1886 }
1887 }
1888
1889 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001890 db.beginTransaction();
1891 try {
Adam Cohen72960972014-01-15 18:13:55 -08001892 for (ContentValues row: allItems) {
1893 if (row == null) continue;
1894 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001895 < 0) {
1896 return;
1897 } else {
1898 count++;
1899 }
1900 }
1901 db.setTransactionSuccessful();
1902 } finally {
1903 db.endTransaction();
1904 }
1905 }
1906
1907 db.beginTransaction();
1908 try {
1909 for (i=0; i<=curScreen; i++) {
1910 final ContentValues values = new ContentValues();
1911 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1912 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1913 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1914 < 0) {
1915 return;
1916 }
1917 }
1918 db.setTransactionSuccessful();
1919 } finally {
1920 db.endTransaction();
1921 }
1922 }
1923 } finally {
1924 c.close();
1925 }
1926 }
1927
1928 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1929 + (curScreen+1) + " screens", true);
1930
1931 // ensure that new screens are created to hold these icons
1932 setFlagJustLoadedOldDb();
1933
1934 // Update max IDs; very important since we just grabbed IDs from another database
1935 mMaxItemId = initializeMaxItemId(db);
1936 mMaxScreenId = initializeMaxScreenId(db);
1937 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1938 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001939 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001940
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001941 /**
1942 * Build a query string that will match any row where the column matches
1943 * anything in the values list.
1944 */
1945 static String buildOrWhereString(String column, int[] values) {
1946 StringBuilder selectWhere = new StringBuilder();
1947 for (int i = values.length - 1; i >= 0; i--) {
1948 selectWhere.append(column).append("=").append(values[i]);
1949 if (i > 0) {
1950 selectWhere.append(" OR ");
1951 }
1952 }
1953 return selectWhere.toString();
1954 }
1955
1956 static class SqlArguments {
1957 public final String table;
1958 public final String where;
1959 public final String[] args;
1960
1961 SqlArguments(Uri url, String where, String[] args) {
1962 if (url.getPathSegments().size() == 1) {
1963 this.table = url.getPathSegments().get(0);
1964 this.where = where;
1965 this.args = args;
1966 } else if (url.getPathSegments().size() != 2) {
1967 throw new IllegalArgumentException("Invalid URI: " + url);
1968 } else if (!TextUtils.isEmpty(where)) {
1969 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1970 } else {
1971 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001972 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001973 this.args = null;
1974 }
1975 }
1976
1977 SqlArguments(Uri url) {
1978 if (url.getPathSegments().size() == 1) {
1979 table = url.getPathSegments().get(0);
1980 where = null;
1981 args = null;
1982 } else {
1983 throw new IllegalArgumentException("Invalid URI: " + url);
1984 }
1985 }
1986 }
Adam Cohen72960972014-01-15 18:13:55 -08001987}