blob: 2a645255c1ecb20947fb5e481e4c1c3b9703a665 [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 Cohen71e03b92014-02-21 14:09:53 -080077 private static final int DATABASE_VERSION = 17;
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
Winson Chungc763c4e2013-07-19 13:49:06 -0700495 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400496 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700497 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
498 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700499 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
500 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700501 editor.commit();
502 }
503
Winson Chungc763c4e2013-07-19 13:49:06 -0700504 private void setFlagEmptyDbCreated() {
505 String spKey = LauncherAppState.getSharedPreferencesKey();
506 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
507 SharedPreferences.Editor editor = sp.edit();
508 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
509 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
510 editor.commit();
511 }
512
513 // We rearrange the screens from the old launcher
514 // 12345 -> 34512
515 private long upgradeLauncherDb_permuteScreens(long screen) {
516 if (screen >= 2) {
517 return screen - 2;
518 } else {
519 return screen + 3;
520 }
521 }
522
523 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
524 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800525 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800526 boolean converted = false;
527
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800528 final ContentResolver resolver = mContext.getContentResolver();
529 Cursor cursor = null;
530
531 try {
532 cursor = resolver.query(uri, null, null, null, null);
533 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700534 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800535 }
536
537 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700538 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800539 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700540 if (cursor.getCount() > 0) {
541 converted = copyFromCursor(db, cursor, cb) > 0;
542 if (converted && deleteRows) {
543 resolver.delete(uri, null, null);
544 }
545 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546 } finally {
547 cursor.close();
548 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700550
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700552 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800553 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800554 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700555
556 // Update max item id
557 mMaxItemId = initializeMaxItemId(db);
558 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 }
560
561 return converted;
562 }
563
Winson Chungc763c4e2013-07-19 13:49:06 -0700564 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700565 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800566 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
567 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
568 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
569 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
570 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
571 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
572 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
573 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
574 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
575 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
576 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
577 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
578 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
579
580 ContentValues[] rows = new ContentValues[c.getCount()];
581 int i = 0;
582 while (c.moveToNext()) {
583 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700584 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
586 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
587 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
588 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
589 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
590 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
591 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
592 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700593 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800594 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
595 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
596 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
597 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
598 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700599 if (cb != null) {
600 cb.onRow(values);
601 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 rows[i++] = values;
603 }
604
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700606 if (i > 0) {
607 db.beginTransaction();
608 try {
609 int numValues = rows.length;
610 for (i = 0; i < numValues; i++) {
611 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
612 return 0;
613 } else {
614 total++;
615 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700617 db.setTransactionSuccessful();
618 } finally {
619 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 }
622
623 return total;
624 }
625
626 @Override
627 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700628 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700629
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700631 if (version < 3) {
632 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 db.beginTransaction();
634 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700635 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700637 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700639 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 } catch (SQLException ex) {
641 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800642 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800643 } finally {
644 db.endTransaction();
645 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700646
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700648 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 convertWidgets(db);
650 }
651 }
Romain Guy73b979d2009-06-09 12:57:21 -0700652
653 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800654 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700655 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700656
Romain Guy509cd6a2010-03-23 15:10:56 -0700657 // Where's version 5?
658 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400659 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700660 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
661 // but version 5 on there was the updateContactsShortcuts change
662 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
663 // The updateContactsShortcuts change is idempotent, so running it twice
664 // is okay so we'll do that when upgrading the devices that shipped with it.
665 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800666 // We went from 3 to 5 screens. Move everything 1 to the right
667 db.beginTransaction();
668 try {
669 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
670 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800671 } catch (SQLException ex) {
672 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800673 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800674 } finally {
675 db.endTransaction();
676 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700677
Romain Guy509cd6a2010-03-23 15:10:56 -0700678 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800679 if (updateContactsShortcuts(db)) {
680 version = 6;
681 }
682 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000683
684 if (version < 7) {
685 // Version 7 gets rid of the special search widget.
686 convertWidgets(db);
687 version = 7;
688 }
689
Joe Onorato0589f0f2010-02-08 13:44:00 -0800690 if (version < 8) {
691 // Version 8 (froyo) has the icons all normalized. This should
692 // already be the case in practice, but we now rely on it and don't
693 // resample the images each time.
694 normalizeIcons(db);
695 version = 8;
696 }
697
Winson Chung3d503fb2011-07-13 17:25:49 -0700698 if (version < 9) {
699 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
700 // 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 -0700701 if (mMaxItemId == -1) {
702 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700703 }
704
705 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800706 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700707 version = 9;
708 }
709
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700710 // We bumped the version three time during JB, once to update the launch flags, once to
711 // update the override for the default launch animation and once to set the mimetype
712 // to improve startup performance
713 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700714 // Contact shortcuts need a different set of flags to be launched now
715 // The updateContactsShortcuts change is idempotent, so we can keep using it like
716 // back in the Donut days
717 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700718 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700719 }
720
Adam Cohendcd297f2013-06-18 13:13:40 -0700721 if (version < 13) {
722 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
723 // to persist workspace screens and their relative order.
724 mMaxScreenId = 0;
725
726 // This will never happen in the wild, but when we switch to using workspace
727 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700728 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700729
730 addWorkspacesTable(db);
731 version = 13;
732 }
733
Chris Wrend5e66bf2013-09-16 14:02:29 -0400734 if (version < 14) {
735 db.beginTransaction();
736 try {
737 // Insert new column for holding widget provider name
738 db.execSQL("ALTER TABLE favorites " +
739 "ADD COLUMN appWidgetProvider TEXT;");
740 db.setTransactionSuccessful();
741 version = 14;
742 } catch (SQLException ex) {
743 // Old version remains, which means we wipe old data
744 Log.e(TAG, ex.getMessage(), ex);
745 } finally {
746 db.endTransaction();
747 }
748 }
749
Chris Wren1ada10d2013-09-13 18:01:38 -0400750 if (version < 15) {
751 db.beginTransaction();
752 try {
753 // Insert new column for holding update timestamp
754 db.execSQL("ALTER TABLE favorites " +
755 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
756 db.execSQL("ALTER TABLE workspaceScreens " +
757 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
758 db.setTransactionSuccessful();
759 version = 15;
760 } catch (SQLException ex) {
761 // Old version remains, which means we wipe old data
762 Log.e(TAG, ex.getMessage(), ex);
763 } finally {
764 db.endTransaction();
765 }
766 }
767
Chris Wrenf4d08112014-01-16 18:13:56 -0500768
769 if (version < 16) {
770 db.beginTransaction();
771 try {
772 // Insert new column for holding restore status
773 db.execSQL("ALTER TABLE favorites " +
774 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
775 db.setTransactionSuccessful();
776 version = 16;
777 } catch (SQLException ex) {
778 // Old version remains, which means we wipe old data
779 Log.e(TAG, ex.getMessage(), ex);
780 } finally {
781 db.endTransaction();
782 }
783 }
784
Adam Cohen71e03b92014-02-21 14:09:53 -0800785 if (version < 17) {
786 // We use the db version upgrade here to identify users who may not have seen
787 // clings yet (because they weren't available), but for whom the clings are now
788 // available (tablet users). Because one of the possible cling flows (migration)
789 // is very destructive (wipes out workspaces), we want to prevent this from showing
790 // until clear data. We do so by marking that the clings have been shown.
791 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
792 version = 17;
793 }
794
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800795 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800796 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800797 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700798 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
799
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800800 onCreate(db);
801 }
802 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800803
804 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800805 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
806 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
807
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700808 Cursor c = null;
809 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800810 db.beginTransaction();
811 try {
812 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700813 c = db.query(TABLE_FAVORITES,
814 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800815 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700816 if (c == null) return false;
817
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800818 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700819
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800820 final int idIndex = c.getColumnIndex(Favorites._ID);
821 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700822
823 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800824 long favoriteId = c.getLong(idIndex);
825 final String intentUri = c.getString(intentIndex);
826 if (intentUri != null) {
827 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700828 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800829 android.util.Log.d("Home", intent.toString());
830 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700831 if (uri != null) {
832 final String data = uri.toString();
833 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
834 actionQuickContact.equals(intent.getAction())) &&
835 (data.startsWith("content://contacts/people/") ||
836 data.startsWith("content://com.android.contacts/" +
837 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800838
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700839 final Intent newIntent = new Intent(actionQuickContact);
840 // When starting from the launcher, start in a new, cleared task
841 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
842 // clear the whole thing preemptively here since
843 // QuickContactActivity will finish itself when launching other
844 // detail activities.
845 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
846 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700847 newIntent.putExtra(
848 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700849 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700850 // Determine the type and also put that in the shortcut
851 // (that can speed up launch a bit)
852 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800853
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700854 final ContentValues values = new ContentValues();
855 values.put(LauncherSettings.Favorites.INTENT,
856 newIntent.toUri(0));
857
858 String updateWhere = Favorites._ID + "=" + favoriteId;
859 db.update(TABLE_FAVORITES, values, updateWhere, null);
860 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800861 }
862 } catch (RuntimeException ex) {
863 Log.e(TAG, "Problem upgrading shortcut", ex);
864 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700865 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800866 }
867 }
868 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700869
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800870 db.setTransactionSuccessful();
871 } catch (SQLException ex) {
872 Log.w(TAG, "Problem while upgrading contacts", ex);
873 return false;
874 } finally {
875 db.endTransaction();
876 if (c != null) {
877 c.close();
878 }
879 }
880
881 return true;
882 }
883
Joe Onorato0589f0f2010-02-08 13:44:00 -0800884 private void normalizeIcons(SQLiteDatabase db) {
885 Log.d(TAG, "normalizing icons");
886
Joe Onorato346e1292010-02-18 10:34:24 -0500887 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800888 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400889 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800890 try {
891 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400892 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600893 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800894
895 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
896 Favorites.ICON_TYPE_BITMAP, null);
897
898 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
899 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
900
901 while (c.moveToNext()) {
902 long id = c.getLong(idIndex);
903 byte[] data = c.getBlob(iconIndex);
904 try {
905 Bitmap bitmap = Utilities.resampleIconBitmap(
906 BitmapFactory.decodeByteArray(data, 0, data.length),
907 mContext);
908 if (bitmap != null) {
909 update.bindLong(1, id);
910 data = ItemInfo.flattenBitmap(bitmap);
911 if (data != null) {
912 update.bindBlob(2, data);
913 update.execute();
914 }
915 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800916 }
917 } catch (Exception e) {
918 if (!logged) {
919 Log.e(TAG, "Failed normalizing icon " + id, e);
920 } else {
921 Log.e(TAG, "Also failed normalizing icon " + id);
922 }
923 logged = true;
924 }
925 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000926 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800927 } catch (SQLException ex) {
928 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
929 } finally {
930 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400931 if (update != null) {
932 update.close();
933 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800934 if (c != null) {
935 c.close();
936 }
937 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700938 }
939
940 // Generates a new ID to use for an object in your database. This method should be only
941 // called from the main UI thread. As an exception, we do call it when we call the
942 // constructor from the worker thread; however, this doesn't extend until after the
943 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
944 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 public long generateNewItemId() {
946 if (mMaxItemId < 0) {
947 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700948 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700949 mMaxItemId += 1;
950 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700951 }
952
Winson Chungc763c4e2013-07-19 13:49:06 -0700953 public void updateMaxItemId(long id) {
954 mMaxItemId = id + 1;
955 }
956
Chris Wren5dee7af2013-12-20 17:22:11 -0500957 public void checkId(String table, ContentValues values) {
958 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
959 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
960 mMaxScreenId = Math.max(id, mMaxScreenId);
961 } else {
962 mMaxItemId = Math.max(id, mMaxItemId);
963 }
964 }
965
Adam Cohendcd297f2013-06-18 13:13:40 -0700966 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700967 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
968
969 // get the result
970 final int maxIdIndex = 0;
971 long id = -1;
972 if (c != null && c.moveToNext()) {
973 id = c.getLong(maxIdIndex);
974 }
Michael Jurka5130e402011-10-13 04:55:35 -0700975 if (c != null) {
976 c.close();
977 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700978
979 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700980 throw new RuntimeException("Error: could not query max item id");
981 }
982
983 return id;
984 }
985
986 // Generates a new ID to use for an workspace screen in your database. This method
987 // should be only called from the main UI thread. As an exception, we do call it when we
988 // call the constructor from the worker thread; however, this doesn't extend until after the
989 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
990 // after that point
991 public long generateNewScreenId() {
992 if (mMaxScreenId < 0) {
993 throw new RuntimeException("Error: max screen id was not initialized");
994 }
995 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800996 // Log to disk
997 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 return mMaxScreenId;
999 }
1000
1001 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001002 // Log to disk
1003 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 mMaxScreenId = maxScreenId;
1005 }
1006
1007 private long initializeMaxScreenId(SQLiteDatabase db) {
1008 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1009
1010 // get the result
1011 final int maxIdIndex = 0;
1012 long id = -1;
1013 if (c != null && c.moveToNext()) {
1014 id = c.getLong(maxIdIndex);
1015 }
1016 if (c != null) {
1017 c.close();
1018 }
1019
1020 if (id == -1) {
1021 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001022 }
1023
Winson Chunga90303b2013-11-15 13:05:06 -08001024 // Log to disk
1025 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001026 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001027 }
1028
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001029 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001030 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001031 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001032 */
1033 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001034 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001035 final int[] bindSources = new int[] {
1036 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1037 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001038 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001039 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001040
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001041 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001042
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001043 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001044
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001045 db.beginTransaction();
1046 try {
1047 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001048 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001049 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001050
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001051 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001052
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001053 final ContentValues values = new ContentValues();
1054 while (c != null && c.moveToNext()) {
1055 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001056 int favoriteType = c.getInt(1);
1057
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001058 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001059 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001060 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001061
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001062 if (LOGD) {
1063 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1064 + " for favoriteId=" + favoriteId);
1065 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001066 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001067 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1068 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1069
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001070 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001071 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1072 values.put(LauncherSettings.Favorites.SPANX, 4);
1073 values.put(LauncherSettings.Favorites.SPANY, 1);
1074 } else {
1075 values.put(LauncherSettings.Favorites.SPANX, 2);
1076 values.put(LauncherSettings.Favorites.SPANY, 2);
1077 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001078
1079 String updateWhere = Favorites._ID + "=" + favoriteId;
1080 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001081
Bjorn Bringert34251342009-12-15 13:33:11 +00001082 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001083 // TODO: check return value
1084 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001085 new ComponentName("com.android.alarmclock",
1086 "com.android.alarmclock.AnalogAppWidgetProvider"));
1087 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001088 // TODO: check return value
1089 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001090 new ComponentName("com.android.camera",
1091 "com.android.camera.PhotoAppWidgetProvider"));
1092 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001093 // TODO: check return value
1094 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001095 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001096 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001097 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001098 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001099 }
1100 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001101
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001102 db.setTransactionSuccessful();
1103 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001104 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001105 } finally {
1106 db.endTransaction();
1107 if (c != null) {
1108 c.close();
1109 }
1110 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001111
1112 // Update max item id
1113 mMaxItemId = initializeMaxItemId(db);
1114 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001115 }
1116
Michael Jurka8b805b12012-04-18 14:23:14 -07001117 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1118 throws XmlPullParserException, IOException {
1119 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001120 while ((type = parser.next()) != XmlPullParser.START_TAG
1121 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001122 ;
1123 }
1124
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001125 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001126 throw new XmlPullParserException("No start tag found");
1127 }
1128
1129 if (!parser.getName().equals(firstElementName)) {
1130 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1131 ", expected " + firstElementName);
1132 }
1133 }
1134
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001135 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 * Loads the default set of favorite packages from an xml file.
1137 *
1138 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001139 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001140 */
Winson Chung6d092682011-11-16 18:43:26 -08001141 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001142 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1143 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1144 ContentValues values = new ContentValues();
1145
Daniel Sandler57dac262013-10-03 13:28:36 -04001146 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1147
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001149 int i = 0;
1150 try {
Winson Chung6d092682011-11-16 18:43:26 -08001151 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001152 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001153 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001155 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001156
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001157 int type;
1158 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1159 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1160
1161 if (type != XmlPullParser.START_TAG) {
1162 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001163 }
1164
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001165 boolean added = false;
1166 final String name = parser.getName();
1167
Daniel Sandler57dac262013-10-03 13:28:36 -04001168 if (TAG_INCLUDE.equals(name)) {
1169 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1170
1171 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1172
1173 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1174 "", resId));
1175
1176 if (resId != 0 && resId != workspaceResourceId) {
1177 // recursively load some more favorites, why not?
1178 i += loadFavorites(db, resId);
1179 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001180 } else {
1181 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1182 }
1183
1184 a.recycle();
1185
1186 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1187 continue;
1188 }
1189
1190 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001191 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1192
Winson Chung3d503fb2011-07-13 17:25:49 -07001193 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1194 if (a.hasValue(R.styleable.Favorite_container)) {
1195 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1196 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001197
Winson Chung6d092682011-11-16 18:43:26 -08001198 String screen = a.getString(R.styleable.Favorite_screen);
1199 String x = a.getString(R.styleable.Favorite_x);
1200 String y = a.getString(R.styleable.Favorite_y);
1201
Winson Chung6d092682011-11-16 18:43:26 -08001202 values.clear();
1203 values.put(LauncherSettings.Favorites.CONTAINER, container);
1204 values.put(LauncherSettings.Favorites.SCREEN, screen);
1205 values.put(LauncherSettings.Favorites.CELLX, x);
1206 values.put(LauncherSettings.Favorites.CELLY, y);
1207
Daniel Sandler57dac262013-10-03 13:28:36 -04001208 if (LOGD) {
1209 final String title = a.getString(R.styleable.Favorite_title);
1210 final String pkg = a.getString(R.styleable.Favorite_packageName);
1211 final String something = title != null ? title : pkg;
1212 Log.v(TAG, String.format(
1213 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1214 "", name,
1215 (something == null ? "" : (" \"" + something + "\"")),
1216 container, screen, x, y));
1217 }
1218
Winson Chung6d092682011-11-16 18:43:26 -08001219 if (TAG_FAVORITE.equals(name)) {
1220 long id = addAppShortcut(db, values, a, packageManager, intent);
1221 added = id >= 0;
1222 } else if (TAG_SEARCH.equals(name)) {
1223 added = addSearchWidget(db, values);
1224 } else if (TAG_CLOCK.equals(name)) {
1225 added = addClockWidget(db, values);
1226 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001227 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001228 } else if (TAG_SHORTCUT.equals(name)) {
1229 long id = addUriShortcut(db, values, a);
1230 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001231 } else if (TAG_RESOLVE.equals(name)) {
1232 // This looks through the contained favorites (or meta-favorites) and
1233 // attempts to add them as shortcuts in the fallback group's location
1234 // until one is added successfully.
1235 added = false;
1236 final int groupDepth = parser.getDepth();
1237 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1238 parser.getDepth() > groupDepth) {
1239 if (type != XmlPullParser.START_TAG) {
1240 continue;
1241 }
1242 final String fallback_item_name = parser.getName();
1243 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1244 R.styleable.Favorite);
1245 if (!added) {
1246 if (TAG_FAVORITE.equals(fallback_item_name)) {
1247 final long id =
1248 addAppShortcut(db, values, ar, packageManager, intent);
1249 added = id >= 0;
1250 } else {
1251 Log.e(TAG, "Fallback groups can contain only favorites "
1252 + ar.toString());
1253 }
1254 }
1255 ar.recycle();
1256 }
Winson Chung6d092682011-11-16 18:43:26 -08001257 } else if (TAG_FOLDER.equals(name)) {
1258 String title;
1259 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1260 if (titleResId != -1) {
1261 title = mContext.getResources().getString(titleResId);
1262 } else {
1263 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001264 }
Winson Chung6d092682011-11-16 18:43:26 -08001265 values.put(LauncherSettings.Favorites.TITLE, title);
1266 long folderId = addFolder(db, values);
1267 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001268
Winson Chung6d092682011-11-16 18:43:26 -08001269 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001270
Winson Chung6d092682011-11-16 18:43:26 -08001271 int folderDepth = parser.getDepth();
1272 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1273 parser.getDepth() > folderDepth) {
1274 if (type != XmlPullParser.START_TAG) {
1275 continue;
1276 }
1277 final String folder_item_name = parser.getName();
1278
1279 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1280 R.styleable.Favorite);
1281 values.clear();
1282 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1283
Daniel Sandler57dac262013-10-03 13:28:36 -04001284 if (LOGD) {
1285 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1286 final String uri = ar.getString(R.styleable.Favorite_uri);
1287 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1288 folder_item_name, uri != null ? uri : pkg));
1289 }
1290
Winson Chung6d092682011-11-16 18:43:26 -08001291 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1292 long id =
1293 addAppShortcut(db, values, ar, packageManager, intent);
1294 if (id >= 0) {
1295 folderItems.add(id);
1296 }
1297 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1298 long id = addUriShortcut(db, values, ar);
1299 if (id >= 0) {
1300 folderItems.add(id);
1301 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001302 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001303 throw new RuntimeException("Folders can " +
1304 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001305 }
Winson Chung6d092682011-11-16 18:43:26 -08001306 ar.recycle();
1307 }
1308 // We can only have folders with >= 2 items, so we need to remove the
1309 // folder and clean up if less than 2 items were included, or some
1310 // failed to add, and less than 2 were actually added
1311 if (folderItems.size() < 2 && folderId >= 0) {
1312 // We just delete the folder and any items that made it
1313 deleteId(db, folderId);
1314 if (folderItems.size() > 0) {
1315 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001316 }
Winson Chung6d092682011-11-16 18:43:26 -08001317 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001318 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001319 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001320 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001321 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001322 }
1323 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001324 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001325 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001326 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001327 } catch (RuntimeException e) {
1328 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001329 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001330
Winson Chungc763c4e2013-07-19 13:49:06 -07001331 // Update the max item id after we have loaded the database
1332 if (mMaxItemId == -1) {
1333 mMaxItemId = initializeMaxItemId(db);
1334 }
1335
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001336 return i;
1337 }
1338
Jason Monk41314972014-03-03 16:11:30 -05001339 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1340 // logical choice for what shortcut should be used for that intent exists, then it is
1341 // added. Otherwise add nothing.
1342 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001343 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001344 final String intentUri = a.getString(R.styleable.Favorite_uri);
1345
1346 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001347 try {
Jason Monk41314972014-03-03 16:11:30 -05001348 metaIntent = Intent.parseUri(intentUri, 0);
1349 } catch (URISyntaxException e) {
1350 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1351 return -1;
1352 }
1353
1354 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1355 PackageManager.MATCH_DEFAULT_ONLY);
1356 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1357 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1358
1359 // Verify that the result is an app and not just the resolver dialog asking which
1360 // app to use.
1361 if (wouldLaunchResolverActivity(resolved, appList)) {
1362 // If only one of the results is a system app then choose that as the default.
1363 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1364 if (systemApp == null) {
1365 // There is no logical choice for this meta-favorite, so rather than making
1366 // a bad choice just add nothing.
1367 Log.w(TAG, "No preference or single system activity found for "
1368 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001369 return -1;
1370 }
Jason Monk41314972014-03-03 16:11:30 -05001371 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001372 }
Jason Monk41314972014-03-03 16:11:30 -05001373 final ActivityInfo info = resolved.activityInfo;
1374 intent.setComponent(new ComponentName(info.packageName, info.name));
1375 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1376 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1377
1378 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1379 }
1380
1381 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1382 PackageManager packageManager) {
1383 ResolveInfo systemResolve = null;
1384 final int N = appList.size();
1385 for (int i = 0; i < N; ++i) {
1386 try {
1387 ApplicationInfo info = packageManager.getApplicationInfo(
1388 appList.get(i).activityInfo.packageName, 0);
1389 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1390 if (systemResolve != null) {
1391 return null;
1392 } else {
1393 systemResolve = appList.get(i);
1394 }
1395 }
1396 } catch (PackageManager.NameNotFoundException e) {
1397 Log.w(TAG, "Unable to get info about resolve results", e);
1398 return null;
1399 }
1400 }
1401 return systemResolve;
1402 }
1403
1404 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1405 List<ResolveInfo> appList) {
1406 // If the list contains the above resolved activity, then it can't be
1407 // ResolverActivity itself.
1408 for (int i = 0; i < appList.size(); ++i) {
1409 ResolveInfo tmp = appList.get(i);
1410 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1411 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1412 return false;
1413 }
1414 }
1415 return true;
1416 }
1417
1418 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1419 PackageManager packageManager, Intent intent) {
1420 if (a.hasValue(R.styleable.Favorite_packageName)
1421 && a.hasValue(R.styleable.Favorite_className)) {
1422 ActivityInfo info;
1423 String packageName = a.getString(R.styleable.Favorite_packageName);
1424 String className = a.getString(R.styleable.Favorite_className);
1425 try {
1426 ComponentName cn;
1427 try {
1428 cn = new ComponentName(packageName, className);
1429 info = packageManager.getActivityInfo(cn, 0);
1430 } catch (PackageManager.NameNotFoundException nnfe) {
1431 String[] packages = packageManager.currentToCanonicalPackageNames(
1432 new String[] { packageName });
1433 cn = new ComponentName(packages[0], className);
1434 info = packageManager.getActivityInfo(cn, 0);
1435 }
1436 intent.setComponent(cn);
1437 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1438 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1439
1440 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1441 intent);
1442 } catch (PackageManager.NameNotFoundException e) {
1443 Log.w(TAG, "Unable to add favorite: " + packageName +
1444 "/" + className, e);
1445 }
1446 return -1;
1447 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1448 // If no component specified try to find a shortcut to add from the URI.
1449 return addAppShortcutByUri(db, values, a, packageManager, intent);
1450 } else {
1451 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1452 return -1;
1453 }
1454 }
1455
1456 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1457 Intent intent) {
1458 long id = generateNewItemId();
1459 values.put(Favorites.INTENT, intent.toUri(0));
1460 values.put(Favorites.TITLE, title);
1461 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1462 values.put(Favorites.SPANX, 1);
1463 values.put(Favorites.SPANY, 1);
1464 values.put(Favorites._ID, id);
1465 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1466 return -1;
1467 } else {
1468 return id;
1469 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001470 }
1471
1472 private long addFolder(SQLiteDatabase db, ContentValues values) {
1473 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1474 values.put(Favorites.SPANX, 1);
1475 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001476 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001477 values.put(Favorites._ID, id);
1478 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1479 return -1;
1480 } else {
1481 return id;
1482 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001483 }
1484
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001485 private ComponentName getSearchWidgetProvider() {
1486 SearchManager searchManager =
1487 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1488 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1489 if (searchComponent == null) return null;
1490 return getProviderInPackage(searchComponent.getPackageName());
1491 }
1492
1493 /**
1494 * Gets an appwidget provider from the given package. If the package contains more than
1495 * one appwidget provider, an arbitrary one is returned.
1496 */
1497 private ComponentName getProviderInPackage(String packageName) {
1498 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1499 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1500 if (providers == null) return null;
1501 final int providerCount = providers.size();
1502 for (int i = 0; i < providerCount; i++) {
1503 ComponentName provider = providers.get(i).provider;
1504 if (provider != null && provider.getPackageName().equals(packageName)) {
1505 return provider;
1506 }
1507 }
1508 return null;
1509 }
1510
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001511 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001512 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001513 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001514 }
1515
1516 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001517 ComponentName cn = new ComponentName("com.android.alarmclock",
1518 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001519 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001520 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001521
Winson Chungb3302ae2012-05-01 10:19:14 -07001522 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1523 SQLiteDatabase db, ContentValues values, TypedArray a,
1524 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001525
Mike Cleronb87bd162009-10-30 16:36:56 -07001526 String packageName = a.getString(R.styleable.Favorite_packageName);
1527 String className = a.getString(R.styleable.Favorite_className);
1528
1529 if (packageName == null || className == null) {
1530 return false;
1531 }
Romain Guy693599f2010-03-23 10:58:18 -07001532
1533 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001534 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001535 try {
1536 packageManager.getReceiverInfo(cn, 0);
1537 } catch (Exception e) {
1538 String[] packages = packageManager.currentToCanonicalPackageNames(
1539 new String[] { packageName });
1540 cn = new ComponentName(packages[0], className);
1541 try {
1542 packageManager.getReceiverInfo(cn, 0);
1543 } catch (Exception e1) {
1544 hasPackage = false;
1545 }
1546 }
1547
1548 if (hasPackage) {
1549 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1550 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001551
1552 // Read the extras
1553 Bundle extras = new Bundle();
1554 int widgetDepth = parser.getDepth();
1555 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1556 parser.getDepth() > widgetDepth) {
1557 if (type != XmlPullParser.START_TAG) {
1558 continue;
1559 }
1560
1561 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1562 if (TAG_EXTRA.equals(parser.getName())) {
1563 String key = ar.getString(R.styleable.Extra_key);
1564 String value = ar.getString(R.styleable.Extra_value);
1565 if (key != null && value != null) {
1566 extras.putString(key, value);
1567 } else {
1568 throw new RuntimeException("Widget extras must have a key and value");
1569 }
1570 } else {
1571 throw new RuntimeException("Widgets can contain only extras");
1572 }
1573 ar.recycle();
1574 }
1575
1576 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001577 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001578
Romain Guy693599f2010-03-23 10:58:18 -07001579 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001580 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001581 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001582 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001583 boolean allocatedAppWidgets = false;
1584 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1585
1586 try {
1587 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001588
Mike Cleronb87bd162009-10-30 16:36:56 -07001589 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001590 values.put(Favorites.SPANX, spanX);
1591 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001592 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001593 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001594 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001595 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001596
1597 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001598
Michael Jurka8b805b12012-04-18 14:23:14 -07001599 // TODO: need to check return value
1600 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001601
1602 // Send a broadcast to configure the widget
1603 if (extras != null && !extras.isEmpty()) {
1604 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1605 intent.setComponent(cn);
1606 intent.putExtras(extras);
1607 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1608 mContext.sendBroadcast(intent);
1609 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001610 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001611 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001612 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001613
Mike Cleronb87bd162009-10-30 16:36:56 -07001614 return allocatedAppWidgets;
1615 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001616
1617 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001618 TypedArray a) {
1619 Resources r = mContext.getResources();
1620
1621 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1622 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1623
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001624 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001625 String uri = null;
1626 try {
1627 uri = a.getString(R.styleable.Favorite_uri);
1628 intent = Intent.parseUri(uri, 0);
1629 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001630 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001631 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001632 }
1633
1634 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001635 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001636 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001637 }
1638
Adam Cohendcd297f2013-06-18 13:13:40 -07001639 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001640 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1641 values.put(Favorites.INTENT, intent.toUri(0));
1642 values.put(Favorites.TITLE, r.getString(titleResId));
1643 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1644 values.put(Favorites.SPANX, 1);
1645 values.put(Favorites.SPANY, 1);
1646 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1647 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1648 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001649 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001650
Adam Cohen228da5a2011-07-27 22:23:47 -07001651 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1652 return -1;
1653 }
1654 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001655 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001656
1657 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1658 final ContentResolver resolver = mContext.getContentResolver();
1659 Cursor c = null;
1660 int count = 0;
1661 int curScreen = 0;
1662
1663 try {
1664 c = resolver.query(uri, null, null, null, "title ASC");
1665 } catch (Exception e) {
1666 // Ignore
1667 }
1668
Dan Sandlerd5024042014-01-09 15:01:33 -05001669 // We already have a favorites database in the old provider
1670 if (c != null) {
1671 try {
1672 if (c.getCount() > 0) {
1673 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1674 final int intentIndex
1675 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1676 final int titleIndex
1677 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1678 final int iconTypeIndex
1679 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1680 final int iconIndex
1681 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1682 final int iconPackageIndex
1683 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1684 final int iconResourceIndex
1685 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1686 final int containerIndex
1687 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1688 final int itemTypeIndex
1689 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1690 final int screenIndex
1691 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1692 final int cellXIndex
1693 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1694 final int cellYIndex
1695 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1696 final int uriIndex
1697 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1698 final int displayModeIndex
1699 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1700
1701 int i = 0;
1702 int curX = 0;
1703 int curY = 0;
1704
1705 final LauncherAppState app = LauncherAppState.getInstance();
1706 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1707 final int width = (int) grid.numColumns;
1708 final int height = (int) grid.numRows;
1709 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001710 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001711
1712 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1713
Adam Cohen72960972014-01-15 18:13:55 -08001714 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1715 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001716 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001717
1718 while (c.moveToNext()) {
1719 final int itemType = c.getInt(itemTypeIndex);
1720 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1721 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1722 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1723 continue;
1724 }
1725
1726 final int cellX = c.getInt(cellXIndex);
1727 final int cellY = c.getInt(cellYIndex);
1728 final int screen = c.getInt(screenIndex);
1729 int container = c.getInt(containerIndex);
1730 final String intentStr = c.getString(intentIndex);
1731 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001732 + c.getString(titleIndex) + "\" ("
1733 + cellX + "," + cellY + "@"
1734 + LauncherSettings.Favorites.containerToString(container)
1735 + "/" + screen
1736 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001737
1738 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001739
1740 final Intent intent;
1741 final ComponentName cn;
1742 try {
1743 intent = Intent.parseUri(intentStr, 0);
1744 } catch (URISyntaxException e) {
1745 // bogus intent?
1746 Launcher.addDumpLog(TAG,
1747 "skipping invalid intent uri", true);
1748 continue;
1749 }
1750
1751 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001752 if (TextUtils.isEmpty(intentStr)) {
1753 // no intent? no icon
1754 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1755 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001756 } else if (cn != null &&
1757 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001758 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001759 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001760 "no longer exists.", true);
1761 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001762 } else if (container ==
1763 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1764 // Dedupe icons directly on the workspace
1765
Adam Cohen556f6132014-01-15 15:18:08 -08001766 // Canonicalize
1767 // the Play Store sets the package parameter, but Launcher
1768 // does not, so we clear that out to keep them the same
1769 intent.setPackage(null);
1770 final String key = intent.toUri(0);
1771 if (seenIntents.contains(key)) {
1772 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001773 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001774 } else {
1775 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001776 }
1777 }
1778 }
1779
1780 ContentValues values = new ContentValues(c.getColumnCount());
1781 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1782 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1783 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1784 values.put(LauncherSettings.Favorites.ICON_TYPE,
1785 c.getInt(iconTypeIndex));
1786 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1787 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1788 c.getString(iconPackageIndex));
1789 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1790 c.getString(iconResourceIndex));
1791 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1792 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1793 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1794 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1795 c.getInt(displayModeIndex));
1796
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001797 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1798 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001799 }
1800
1801 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1802 // In a folder or in the hotseat, preserve position
1803 values.put(LauncherSettings.Favorites.SCREEN, screen);
1804 values.put(LauncherSettings.Favorites.CELLX, cellX);
1805 values.put(LauncherSettings.Favorites.CELLY, cellY);
1806 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001807 // For items contained directly on one of the workspace screen,
1808 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001809 }
1810
1811 values.put(LauncherSettings.Favorites.CONTAINER, container);
1812
Adam Cohen72960972014-01-15 18:13:55 -08001813 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1814 shortcuts.add(values);
1815 } else {
1816 folders.add(values);
1817 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001818 }
1819
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001820 // Now that we have all the hotseat icons, let's go through them left-right
1821 // and assign valid locations for them in the new hotseat
1822 final int N = hotseat.size();
1823 for (int idx=0; idx<N; idx++) {
1824 int hotseatX = hotseat.keyAt(idx);
1825 ContentValues values = hotseat.valueAt(idx);
1826
1827 if (hotseatX == grid.hotseatAllAppsRank) {
1828 // let's drop this in the next available hole in the hotseat
1829 while (++hotseatX < hotseatWidth) {
1830 if (hotseat.get(hotseatX) == null) {
1831 // found a spot! move it here
1832 values.put(LauncherSettings.Favorites.SCREEN,
1833 hotseatX);
1834 break;
1835 }
1836 }
1837 }
1838 if (hotseatX >= hotseatWidth) {
1839 // no room for you in the hotseat? it's off to the desktop with you
1840 values.put(LauncherSettings.Favorites.CONTAINER,
1841 Favorites.CONTAINER_DESKTOP);
1842 }
1843 }
1844
Adam Cohen72960972014-01-15 18:13:55 -08001845 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1846 // Folders first
1847 allItems.addAll(folders);
1848 // Then shortcuts
1849 allItems.addAll(shortcuts);
1850
1851 // Layout all the folders
1852 for (ContentValues values: allItems) {
1853 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1854 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1855 // Hotseat items and folder items have already had their
1856 // location information set. Nothing to be done here.
1857 continue;
1858 }
1859 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1860 values.put(LauncherSettings.Favorites.CELLX, curX);
1861 values.put(LauncherSettings.Favorites.CELLY, curY);
1862 curX = (curX + 1) % width;
1863 if (curX == 0) {
1864 curY = (curY + 1);
1865 }
1866 // Leave the last row of icons blank on every screen
1867 if (curY == height - 1) {
1868 curScreen = (int) generateNewScreenId();
1869 curY = 0;
1870 }
1871 }
1872
1873 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001874 db.beginTransaction();
1875 try {
Adam Cohen72960972014-01-15 18:13:55 -08001876 for (ContentValues row: allItems) {
1877 if (row == null) continue;
1878 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001879 < 0) {
1880 return;
1881 } else {
1882 count++;
1883 }
1884 }
1885 db.setTransactionSuccessful();
1886 } finally {
1887 db.endTransaction();
1888 }
1889 }
1890
1891 db.beginTransaction();
1892 try {
1893 for (i=0; i<=curScreen; i++) {
1894 final ContentValues values = new ContentValues();
1895 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1896 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1897 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1898 < 0) {
1899 return;
1900 }
1901 }
1902 db.setTransactionSuccessful();
1903 } finally {
1904 db.endTransaction();
1905 }
1906 }
1907 } finally {
1908 c.close();
1909 }
1910 }
1911
1912 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1913 + (curScreen+1) + " screens", true);
1914
1915 // ensure that new screens are created to hold these icons
1916 setFlagJustLoadedOldDb();
1917
1918 // Update max IDs; very important since we just grabbed IDs from another database
1919 mMaxItemId = initializeMaxItemId(db);
1920 mMaxScreenId = initializeMaxScreenId(db);
1921 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1922 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001923 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001924
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001925 /**
1926 * Build a query string that will match any row where the column matches
1927 * anything in the values list.
1928 */
1929 static String buildOrWhereString(String column, int[] values) {
1930 StringBuilder selectWhere = new StringBuilder();
1931 for (int i = values.length - 1; i >= 0; i--) {
1932 selectWhere.append(column).append("=").append(values[i]);
1933 if (i > 0) {
1934 selectWhere.append(" OR ");
1935 }
1936 }
1937 return selectWhere.toString();
1938 }
1939
1940 static class SqlArguments {
1941 public final String table;
1942 public final String where;
1943 public final String[] args;
1944
1945 SqlArguments(Uri url, String where, String[] args) {
1946 if (url.getPathSegments().size() == 1) {
1947 this.table = url.getPathSegments().get(0);
1948 this.where = where;
1949 this.args = args;
1950 } else if (url.getPathSegments().size() != 2) {
1951 throw new IllegalArgumentException("Invalid URI: " + url);
1952 } else if (!TextUtils.isEmpty(where)) {
1953 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1954 } else {
1955 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001956 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001957 this.args = null;
1958 }
1959 }
1960
1961 SqlArguments(Uri url) {
1962 if (url.getPathSegments().size() == 1) {
1963 table = url.getPathSegments().get(0);
1964 where = null;
1965 args = null;
1966 } else {
1967 throw new IllegalArgumentException("Invalid URI: " + url);
1968 }
1969 }
1970 }
Adam Cohen72960972014-01-15 18:13:55 -08001971}