blob: 21b1799182892cb3cd934116baba099f3c5d9834 [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 Cohenf9c14de2014-04-17 18:20:45 -070077 private static final int DATABASE_VERSION = 19;
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(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400332 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 }
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
Jason Monk0bfcceb2014-03-21 15:42:06 -0400469 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500470 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
471 // If we fail, then set a flag to load the default workspace
472 setFlagEmptyDbCreated();
473 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 }
475 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500476 // Right now, in non-default workspace cases, we want to run the final
477 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
478 // set that flag too.
479 setFlagJustLoadedOldDb();
480 } else {
481 // Fresh and clean launcher DB.
482 mMaxItemId = initializeMaxItemId(db);
483 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 }
485 }
486
Adam Cohendcd297f2013-06-18 13:13:40 -0700487 private void addWorkspacesTable(SQLiteDatabase db) {
488 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
489 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
491 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700492 ");");
493 }
494
Adam Cohen119285e2014-04-02 16:59:08 -0700495 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700496 // Delete items directly on the workspace who's screen id doesn't exist
497 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
498 // AND container = -100"
499 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
500 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700501 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700502 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
503 " AND " +
504 LauncherSettings.Favorites.CONTAINER + " = " +
505 LauncherSettings.Favorites.CONTAINER_DESKTOP;
506 db.execSQL(removeOrphanedDesktopItems);
507
508 // Delete items contained in folders which no longer exist (after above statement)
509 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
510 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
511 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
512 " WHERE " +
513 LauncherSettings.Favorites.CONTAINER + " <> " +
514 LauncherSettings.Favorites.CONTAINER_DESKTOP +
515 " AND "
516 + LauncherSettings.Favorites.CONTAINER + " <> " +
517 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
518 " AND "
519 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
520 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
521 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
522 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
523 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700524 }
525
Winson Chungc763c4e2013-07-19 13:49:06 -0700526 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400527 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700528 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
529 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700530 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
531 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700532 editor.commit();
533 }
534
Winson Chungc763c4e2013-07-19 13:49:06 -0700535 private void setFlagEmptyDbCreated() {
536 String spKey = LauncherAppState.getSharedPreferencesKey();
537 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
538 SharedPreferences.Editor editor = sp.edit();
539 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
540 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
541 editor.commit();
542 }
543
544 // We rearrange the screens from the old launcher
545 // 12345 -> 34512
546 private long upgradeLauncherDb_permuteScreens(long screen) {
547 if (screen >= 2) {
548 return screen - 2;
549 } else {
550 return screen + 3;
551 }
552 }
553
554 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
555 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800556 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800557 boolean converted = false;
558
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 final ContentResolver resolver = mContext.getContentResolver();
560 Cursor cursor = null;
561
562 try {
563 cursor = resolver.query(uri, null, null, null, null);
564 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700565 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800566 }
567
568 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700569 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800570 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700571 if (cursor.getCount() > 0) {
572 converted = copyFromCursor(db, cursor, cb) > 0;
573 if (converted && deleteRows) {
574 resolver.delete(uri, null, null);
575 }
576 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800577 } finally {
578 cursor.close();
579 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800580 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700581
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700583 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800584 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700586
587 // Update max item id
588 mMaxItemId = initializeMaxItemId(db);
589 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800590 }
591
592 return converted;
593 }
594
Winson Chungc763c4e2013-07-19 13:49:06 -0700595 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700596 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
598 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
599 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
600 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
601 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
602 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
603 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
604 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
605 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
606 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
607 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
608 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
609 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
610
611 ContentValues[] rows = new ContentValues[c.getCount()];
612 int i = 0;
613 while (c.moveToNext()) {
614 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700615 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
617 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
618 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
619 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
620 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
621 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
622 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
623 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700624 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
626 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
627 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
628 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
629 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700630 if (cb != null) {
631 cb.onRow(values);
632 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 rows[i++] = values;
634 }
635
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700637 if (i > 0) {
638 db.beginTransaction();
639 try {
640 int numValues = rows.length;
641 for (i = 0; i < numValues; i++) {
642 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
643 return 0;
644 } else {
645 total++;
646 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700648 db.setTransactionSuccessful();
649 } finally {
650 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652 }
653
654 return total;
655 }
656
657 @Override
658 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700659 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700660
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800661 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700662 if (version < 3) {
663 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664 db.beginTransaction();
665 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700666 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700668 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800669 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700670 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -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);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800674 } finally {
675 db.endTransaction();
676 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700677
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700679 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800680 convertWidgets(db);
681 }
682 }
Romain Guy73b979d2009-06-09 12:57:21 -0700683
684 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800685 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700686 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700687
Romain Guy509cd6a2010-03-23 15:10:56 -0700688 // Where's version 5?
689 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400690 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700691 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
692 // but version 5 on there was the updateContactsShortcuts change
693 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
694 // The updateContactsShortcuts change is idempotent, so running it twice
695 // is okay so we'll do that when upgrading the devices that shipped with it.
696 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800697 // We went from 3 to 5 screens. Move everything 1 to the right
698 db.beginTransaction();
699 try {
700 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
701 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800702 } catch (SQLException ex) {
703 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800704 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800705 } finally {
706 db.endTransaction();
707 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700708
Romain Guy509cd6a2010-03-23 15:10:56 -0700709 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800710 if (updateContactsShortcuts(db)) {
711 version = 6;
712 }
713 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000714
715 if (version < 7) {
716 // Version 7 gets rid of the special search widget.
717 convertWidgets(db);
718 version = 7;
719 }
720
Joe Onorato0589f0f2010-02-08 13:44:00 -0800721 if (version < 8) {
722 // Version 8 (froyo) has the icons all normalized. This should
723 // already be the case in practice, but we now rely on it and don't
724 // resample the images each time.
725 normalizeIcons(db);
726 version = 8;
727 }
728
Winson Chung3d503fb2011-07-13 17:25:49 -0700729 if (version < 9) {
730 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
731 // 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 -0700732 if (mMaxItemId == -1) {
733 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700734 }
735
736 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800737 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700738 version = 9;
739 }
740
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700741 // We bumped the version three time during JB, once to update the launch flags, once to
742 // update the override for the default launch animation and once to set the mimetype
743 // to improve startup performance
744 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700745 // Contact shortcuts need a different set of flags to be launched now
746 // The updateContactsShortcuts change is idempotent, so we can keep using it like
747 // back in the Donut days
748 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700749 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700750 }
751
Adam Cohendcd297f2013-06-18 13:13:40 -0700752 if (version < 13) {
753 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
754 // to persist workspace screens and their relative order.
755 mMaxScreenId = 0;
756
757 // This will never happen in the wild, but when we switch to using workspace
758 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700759 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700760
761 addWorkspacesTable(db);
762 version = 13;
763 }
764
Chris Wrend5e66bf2013-09-16 14:02:29 -0400765 if (version < 14) {
766 db.beginTransaction();
767 try {
768 // Insert new column for holding widget provider name
769 db.execSQL("ALTER TABLE favorites " +
770 "ADD COLUMN appWidgetProvider TEXT;");
771 db.setTransactionSuccessful();
772 version = 14;
773 } catch (SQLException ex) {
774 // Old version remains, which means we wipe old data
775 Log.e(TAG, ex.getMessage(), ex);
776 } finally {
777 db.endTransaction();
778 }
779 }
780
Chris Wren1ada10d2013-09-13 18:01:38 -0400781 if (version < 15) {
782 db.beginTransaction();
783 try {
784 // Insert new column for holding update timestamp
785 db.execSQL("ALTER TABLE favorites " +
786 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
787 db.execSQL("ALTER TABLE workspaceScreens " +
788 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
789 db.setTransactionSuccessful();
790 version = 15;
791 } catch (SQLException ex) {
792 // Old version remains, which means we wipe old data
793 Log.e(TAG, ex.getMessage(), ex);
794 } finally {
795 db.endTransaction();
796 }
797 }
798
Chris Wrenf4d08112014-01-16 18:13:56 -0500799
800 if (version < 16) {
801 db.beginTransaction();
802 try {
803 // Insert new column for holding restore status
804 db.execSQL("ALTER TABLE favorites " +
805 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
806 db.setTransactionSuccessful();
807 version = 16;
808 } catch (SQLException ex) {
809 // Old version remains, which means we wipe old data
810 Log.e(TAG, ex.getMessage(), ex);
811 } finally {
812 db.endTransaction();
813 }
814 }
815
Adam Cohen71e03b92014-02-21 14:09:53 -0800816 if (version < 17) {
817 // We use the db version upgrade here to identify users who may not have seen
818 // clings yet (because they weren't available), but for whom the clings are now
819 // available (tablet users). Because one of the possible cling flows (migration)
820 // is very destructive (wipes out workspaces), we want to prevent this from showing
821 // until clear data. We do so by marking that the clings have been shown.
822 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
823 version = 17;
824 }
825
Adam Cohen119285e2014-04-02 16:59:08 -0700826 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700827 // No-op
828 version = 18;
829 }
830
831 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700832 // Due to a data loss bug, some users may have items associated with screen ids
833 // which no longer exist. Since this can cause other problems, and since the user
834 // will never see these items anyway, we use database upgrade as an opportunity to
835 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700836 removeOrphanedItems(db);
837 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700838 }
839
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800840 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800841 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800842 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700843 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
844
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800845 onCreate(db);
846 }
847 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800848
849 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800850 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
851 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
852
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700853 Cursor c = null;
854 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800855 db.beginTransaction();
856 try {
857 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700858 c = db.query(TABLE_FAVORITES,
859 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800860 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700861 if (c == null) return false;
862
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800863 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700864
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800865 final int idIndex = c.getColumnIndex(Favorites._ID);
866 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700867
868 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800869 long favoriteId = c.getLong(idIndex);
870 final String intentUri = c.getString(intentIndex);
871 if (intentUri != null) {
872 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700873 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800874 android.util.Log.d("Home", intent.toString());
875 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700876 if (uri != null) {
877 final String data = uri.toString();
878 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
879 actionQuickContact.equals(intent.getAction())) &&
880 (data.startsWith("content://contacts/people/") ||
881 data.startsWith("content://com.android.contacts/" +
882 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800883
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700884 final Intent newIntent = new Intent(actionQuickContact);
885 // When starting from the launcher, start in a new, cleared task
886 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
887 // clear the whole thing preemptively here since
888 // QuickContactActivity will finish itself when launching other
889 // detail activities.
890 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
891 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700892 newIntent.putExtra(
893 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700894 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700895 // Determine the type and also put that in the shortcut
896 // (that can speed up launch a bit)
897 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800898
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700899 final ContentValues values = new ContentValues();
900 values.put(LauncherSettings.Favorites.INTENT,
901 newIntent.toUri(0));
902
903 String updateWhere = Favorites._ID + "=" + favoriteId;
904 db.update(TABLE_FAVORITES, values, updateWhere, null);
905 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800906 }
907 } catch (RuntimeException ex) {
908 Log.e(TAG, "Problem upgrading shortcut", ex);
909 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700910 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800911 }
912 }
913 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700914
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800915 db.setTransactionSuccessful();
916 } catch (SQLException ex) {
917 Log.w(TAG, "Problem while upgrading contacts", ex);
918 return false;
919 } finally {
920 db.endTransaction();
921 if (c != null) {
922 c.close();
923 }
924 }
925
926 return true;
927 }
928
Joe Onorato0589f0f2010-02-08 13:44:00 -0800929 private void normalizeIcons(SQLiteDatabase db) {
930 Log.d(TAG, "normalizing icons");
931
Joe Onorato346e1292010-02-18 10:34:24 -0500932 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800933 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400934 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800935 try {
936 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400937 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600938 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800939
940 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
941 Favorites.ICON_TYPE_BITMAP, null);
942
943 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
944 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
945
946 while (c.moveToNext()) {
947 long id = c.getLong(idIndex);
948 byte[] data = c.getBlob(iconIndex);
949 try {
950 Bitmap bitmap = Utilities.resampleIconBitmap(
951 BitmapFactory.decodeByteArray(data, 0, data.length),
952 mContext);
953 if (bitmap != null) {
954 update.bindLong(1, id);
955 data = ItemInfo.flattenBitmap(bitmap);
956 if (data != null) {
957 update.bindBlob(2, data);
958 update.execute();
959 }
960 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800961 }
962 } catch (Exception e) {
963 if (!logged) {
964 Log.e(TAG, "Failed normalizing icon " + id, e);
965 } else {
966 Log.e(TAG, "Also failed normalizing icon " + id);
967 }
968 logged = true;
969 }
970 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000971 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800972 } catch (SQLException ex) {
973 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
974 } finally {
975 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400976 if (update != null) {
977 update.close();
978 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800979 if (c != null) {
980 c.close();
981 }
982 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700983 }
984
985 // Generates a new ID to use for an object in your database. This method should be only
986 // called from the main UI thread. As an exception, we do call it when we call the
987 // constructor from the worker thread; however, this doesn't extend until after the
988 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
989 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700990 public long generateNewItemId() {
991 if (mMaxItemId < 0) {
992 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700993 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 mMaxItemId += 1;
995 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700996 }
997
Winson Chungc763c4e2013-07-19 13:49:06 -0700998 public void updateMaxItemId(long id) {
999 mMaxItemId = id + 1;
1000 }
1001
Chris Wren5dee7af2013-12-20 17:22:11 -05001002 public void checkId(String table, ContentValues values) {
1003 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1004 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1005 mMaxScreenId = Math.max(id, mMaxScreenId);
1006 } else {
1007 mMaxItemId = Math.max(id, mMaxItemId);
1008 }
1009 }
1010
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001012 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1013
1014 // get the result
1015 final int maxIdIndex = 0;
1016 long id = -1;
1017 if (c != null && c.moveToNext()) {
1018 id = c.getLong(maxIdIndex);
1019 }
Michael Jurka5130e402011-10-13 04:55:35 -07001020 if (c != null) {
1021 c.close();
1022 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001023
1024 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001025 throw new RuntimeException("Error: could not query max item id");
1026 }
1027
1028 return id;
1029 }
1030
1031 // Generates a new ID to use for an workspace screen in your database. This method
1032 // should be only called from the main UI thread. As an exception, we do call it when we
1033 // call the constructor from the worker thread; however, this doesn't extend until after the
1034 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1035 // after that point
1036 public long generateNewScreenId() {
1037 if (mMaxScreenId < 0) {
1038 throw new RuntimeException("Error: max screen id was not initialized");
1039 }
1040 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001041 // Log to disk
1042 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001043 return mMaxScreenId;
1044 }
1045
1046 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001047 // Log to disk
1048 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 mMaxScreenId = maxScreenId;
1050 }
1051
1052 private long initializeMaxScreenId(SQLiteDatabase db) {
1053 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1054
1055 // get the result
1056 final int maxIdIndex = 0;
1057 long id = -1;
1058 if (c != null && c.moveToNext()) {
1059 id = c.getLong(maxIdIndex);
1060 }
1061 if (c != null) {
1062 c.close();
1063 }
1064
1065 if (id == -1) {
1066 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001067 }
1068
Winson Chunga90303b2013-11-15 13:05:06 -08001069 // Log to disk
1070 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001071 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001072 }
1073
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001074 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001075 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001076 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001077 */
1078 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001079 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001080 final int[] bindSources = new int[] {
1081 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1082 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001083 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001084 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001085
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001086 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001087
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001088 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001089
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001090 db.beginTransaction();
1091 try {
1092 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001093 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001094 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001095
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001096 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001097
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001098 final ContentValues values = new ContentValues();
1099 while (c != null && c.moveToNext()) {
1100 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001101 int favoriteType = c.getInt(1);
1102
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001103 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001104 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001105 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001106
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001107 if (LOGD) {
1108 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1109 + " for favoriteId=" + favoriteId);
1110 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001111 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001112 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1113 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1114
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001115 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001116 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1117 values.put(LauncherSettings.Favorites.SPANX, 4);
1118 values.put(LauncherSettings.Favorites.SPANY, 1);
1119 } else {
1120 values.put(LauncherSettings.Favorites.SPANX, 2);
1121 values.put(LauncherSettings.Favorites.SPANY, 2);
1122 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001123
1124 String updateWhere = Favorites._ID + "=" + favoriteId;
1125 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001126
Bjorn Bringert34251342009-12-15 13:33:11 +00001127 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001128 // TODO: check return value
1129 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001130 new ComponentName("com.android.alarmclock",
1131 "com.android.alarmclock.AnalogAppWidgetProvider"));
1132 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001133 // TODO: check return value
1134 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001135 new ComponentName("com.android.camera",
1136 "com.android.camera.PhotoAppWidgetProvider"));
1137 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001138 // TODO: check return value
1139 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001140 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001141 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001142 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001143 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001144 }
1145 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001146
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001147 db.setTransactionSuccessful();
1148 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001149 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001150 } finally {
1151 db.endTransaction();
1152 if (c != null) {
1153 c.close();
1154 }
1155 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001156
1157 // Update max item id
1158 mMaxItemId = initializeMaxItemId(db);
1159 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001160 }
1161
Michael Jurka8b805b12012-04-18 14:23:14 -07001162 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1163 throws XmlPullParserException, IOException {
1164 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001165 while ((type = parser.next()) != XmlPullParser.START_TAG
1166 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001167 ;
1168 }
1169
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001170 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001171 throw new XmlPullParserException("No start tag found");
1172 }
1173
1174 if (!parser.getName().equals(firstElementName)) {
1175 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1176 ", expected " + firstElementName);
1177 }
1178 }
1179
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001180 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 * Loads the default set of favorite packages from an xml file.
1182 *
1183 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001184 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001185 */
Winson Chung6d092682011-11-16 18:43:26 -08001186 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001187 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1188 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1189 ContentValues values = new ContentValues();
1190
Daniel Sandler57dac262013-10-03 13:28:36 -04001191 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1192
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001194 int i = 0;
1195 try {
Winson Chung6d092682011-11-16 18:43:26 -08001196 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001197 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001198 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001199
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001200 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001201
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001202 int type;
1203 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1204 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1205
1206 if (type != XmlPullParser.START_TAG) {
1207 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 }
1209
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001210 boolean added = false;
1211 final String name = parser.getName();
1212
Daniel Sandler57dac262013-10-03 13:28:36 -04001213 if (TAG_INCLUDE.equals(name)) {
1214 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1215
1216 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1217
1218 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1219 "", resId));
1220
1221 if (resId != 0 && resId != workspaceResourceId) {
1222 // recursively load some more favorites, why not?
1223 i += loadFavorites(db, resId);
1224 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001225 } else {
1226 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1227 }
1228
1229 a.recycle();
1230
1231 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1232 continue;
1233 }
1234
1235 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001236 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1237
Winson Chung3d503fb2011-07-13 17:25:49 -07001238 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1239 if (a.hasValue(R.styleable.Favorite_container)) {
1240 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1241 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001242
Winson Chung6d092682011-11-16 18:43:26 -08001243 String screen = a.getString(R.styleable.Favorite_screen);
1244 String x = a.getString(R.styleable.Favorite_x);
1245 String y = a.getString(R.styleable.Favorite_y);
1246
Winson Chung6d092682011-11-16 18:43:26 -08001247 values.clear();
1248 values.put(LauncherSettings.Favorites.CONTAINER, container);
1249 values.put(LauncherSettings.Favorites.SCREEN, screen);
1250 values.put(LauncherSettings.Favorites.CELLX, x);
1251 values.put(LauncherSettings.Favorites.CELLY, y);
1252
Daniel Sandler57dac262013-10-03 13:28:36 -04001253 if (LOGD) {
1254 final String title = a.getString(R.styleable.Favorite_title);
1255 final String pkg = a.getString(R.styleable.Favorite_packageName);
1256 final String something = title != null ? title : pkg;
1257 Log.v(TAG, String.format(
1258 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1259 "", name,
1260 (something == null ? "" : (" \"" + something + "\"")),
1261 container, screen, x, y));
1262 }
1263
Winson Chung6d092682011-11-16 18:43:26 -08001264 if (TAG_FAVORITE.equals(name)) {
1265 long id = addAppShortcut(db, values, a, packageManager, intent);
1266 added = id >= 0;
1267 } else if (TAG_SEARCH.equals(name)) {
1268 added = addSearchWidget(db, values);
1269 } else if (TAG_CLOCK.equals(name)) {
1270 added = addClockWidget(db, values);
1271 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001272 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001273 } else if (TAG_SHORTCUT.equals(name)) {
1274 long id = addUriShortcut(db, values, a);
1275 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001276 } else if (TAG_RESOLVE.equals(name)) {
1277 // This looks through the contained favorites (or meta-favorites) and
1278 // attempts to add them as shortcuts in the fallback group's location
1279 // until one is added successfully.
1280 added = false;
1281 final int groupDepth = parser.getDepth();
1282 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1283 parser.getDepth() > groupDepth) {
1284 if (type != XmlPullParser.START_TAG) {
1285 continue;
1286 }
1287 final String fallback_item_name = parser.getName();
1288 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1289 R.styleable.Favorite);
1290 if (!added) {
1291 if (TAG_FAVORITE.equals(fallback_item_name)) {
1292 final long id =
1293 addAppShortcut(db, values, ar, packageManager, intent);
1294 added = id >= 0;
1295 } else {
1296 Log.e(TAG, "Fallback groups can contain only favorites "
1297 + ar.toString());
1298 }
1299 }
1300 ar.recycle();
1301 }
Winson Chung6d092682011-11-16 18:43:26 -08001302 } else if (TAG_FOLDER.equals(name)) {
1303 String title;
1304 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1305 if (titleResId != -1) {
1306 title = mContext.getResources().getString(titleResId);
1307 } else {
1308 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001309 }
Winson Chung6d092682011-11-16 18:43:26 -08001310 values.put(LauncherSettings.Favorites.TITLE, title);
1311 long folderId = addFolder(db, values);
1312 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001313
Winson Chung6d092682011-11-16 18:43:26 -08001314 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001315
Winson Chung6d092682011-11-16 18:43:26 -08001316 int folderDepth = parser.getDepth();
1317 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1318 parser.getDepth() > folderDepth) {
1319 if (type != XmlPullParser.START_TAG) {
1320 continue;
1321 }
1322 final String folder_item_name = parser.getName();
1323
1324 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1325 R.styleable.Favorite);
1326 values.clear();
1327 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1328
Daniel Sandler57dac262013-10-03 13:28:36 -04001329 if (LOGD) {
1330 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1331 final String uri = ar.getString(R.styleable.Favorite_uri);
1332 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1333 folder_item_name, uri != null ? uri : pkg));
1334 }
1335
Winson Chung6d092682011-11-16 18:43:26 -08001336 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1337 long id =
1338 addAppShortcut(db, values, ar, packageManager, intent);
1339 if (id >= 0) {
1340 folderItems.add(id);
1341 }
1342 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1343 long id = addUriShortcut(db, values, ar);
1344 if (id >= 0) {
1345 folderItems.add(id);
1346 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001347 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001348 throw new RuntimeException("Folders can " +
1349 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001350 }
Winson Chung6d092682011-11-16 18:43:26 -08001351 ar.recycle();
1352 }
1353 // We can only have folders with >= 2 items, so we need to remove the
1354 // folder and clean up if less than 2 items were included, or some
1355 // failed to add, and less than 2 were actually added
1356 if (folderItems.size() < 2 && folderId >= 0) {
1357 // We just delete the folder and any items that made it
1358 deleteId(db, folderId);
1359 if (folderItems.size() > 0) {
1360 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001361 }
Winson Chung6d092682011-11-16 18:43:26 -08001362 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001363 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001364 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001365 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001366 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001367 }
1368 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001369 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001370 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001371 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001372 } catch (RuntimeException e) {
1373 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001374 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001375
Winson Chungc763c4e2013-07-19 13:49:06 -07001376 // Update the max item id after we have loaded the database
1377 if (mMaxItemId == -1) {
1378 mMaxItemId = initializeMaxItemId(db);
1379 }
1380
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001381 return i;
1382 }
1383
Jason Monk41314972014-03-03 16:11:30 -05001384 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1385 // logical choice for what shortcut should be used for that intent exists, then it is
1386 // added. Otherwise add nothing.
1387 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001388 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001389 final String intentUri = a.getString(R.styleable.Favorite_uri);
1390
1391 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001392 try {
Jason Monk41314972014-03-03 16:11:30 -05001393 metaIntent = Intent.parseUri(intentUri, 0);
1394 } catch (URISyntaxException e) {
1395 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1396 return -1;
1397 }
1398
1399 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1400 PackageManager.MATCH_DEFAULT_ONLY);
1401 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1402 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1403
1404 // Verify that the result is an app and not just the resolver dialog asking which
1405 // app to use.
1406 if (wouldLaunchResolverActivity(resolved, appList)) {
1407 // If only one of the results is a system app then choose that as the default.
1408 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1409 if (systemApp == null) {
1410 // There is no logical choice for this meta-favorite, so rather than making
1411 // a bad choice just add nothing.
1412 Log.w(TAG, "No preference or single system activity found for "
1413 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001414 return -1;
1415 }
Jason Monk41314972014-03-03 16:11:30 -05001416 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001417 }
Jason Monk41314972014-03-03 16:11:30 -05001418 final ActivityInfo info = resolved.activityInfo;
1419 intent.setComponent(new ComponentName(info.packageName, info.name));
1420 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1421 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1422
1423 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1424 }
1425
1426 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1427 PackageManager packageManager) {
1428 ResolveInfo systemResolve = null;
1429 final int N = appList.size();
1430 for (int i = 0; i < N; ++i) {
1431 try {
1432 ApplicationInfo info = packageManager.getApplicationInfo(
1433 appList.get(i).activityInfo.packageName, 0);
1434 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1435 if (systemResolve != null) {
1436 return null;
1437 } else {
1438 systemResolve = appList.get(i);
1439 }
1440 }
1441 } catch (PackageManager.NameNotFoundException e) {
1442 Log.w(TAG, "Unable to get info about resolve results", e);
1443 return null;
1444 }
1445 }
1446 return systemResolve;
1447 }
1448
1449 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1450 List<ResolveInfo> appList) {
1451 // If the list contains the above resolved activity, then it can't be
1452 // ResolverActivity itself.
1453 for (int i = 0; i < appList.size(); ++i) {
1454 ResolveInfo tmp = appList.get(i);
1455 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1456 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1457 return false;
1458 }
1459 }
1460 return true;
1461 }
1462
1463 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1464 PackageManager packageManager, Intent intent) {
1465 if (a.hasValue(R.styleable.Favorite_packageName)
1466 && a.hasValue(R.styleable.Favorite_className)) {
1467 ActivityInfo info;
1468 String packageName = a.getString(R.styleable.Favorite_packageName);
1469 String className = a.getString(R.styleable.Favorite_className);
1470 try {
1471 ComponentName cn;
1472 try {
1473 cn = new ComponentName(packageName, className);
1474 info = packageManager.getActivityInfo(cn, 0);
1475 } catch (PackageManager.NameNotFoundException nnfe) {
1476 String[] packages = packageManager.currentToCanonicalPackageNames(
1477 new String[] { packageName });
1478 cn = new ComponentName(packages[0], className);
1479 info = packageManager.getActivityInfo(cn, 0);
1480 }
1481 intent.setComponent(cn);
1482 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1483 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1484
1485 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1486 intent);
1487 } catch (PackageManager.NameNotFoundException e) {
1488 Log.w(TAG, "Unable to add favorite: " + packageName +
1489 "/" + className, e);
1490 }
1491 return -1;
1492 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1493 // If no component specified try to find a shortcut to add from the URI.
1494 return addAppShortcutByUri(db, values, a, packageManager, intent);
1495 } else {
1496 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1497 return -1;
1498 }
1499 }
1500
1501 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1502 Intent intent) {
1503 long id = generateNewItemId();
1504 values.put(Favorites.INTENT, intent.toUri(0));
1505 values.put(Favorites.TITLE, title);
1506 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1507 values.put(Favorites.SPANX, 1);
1508 values.put(Favorites.SPANY, 1);
1509 values.put(Favorites._ID, id);
1510 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1511 return -1;
1512 } else {
1513 return id;
1514 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001515 }
1516
1517 private long addFolder(SQLiteDatabase db, ContentValues values) {
1518 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1519 values.put(Favorites.SPANX, 1);
1520 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001521 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001522 values.put(Favorites._ID, id);
1523 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1524 return -1;
1525 } else {
1526 return id;
1527 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001528 }
1529
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001530 private ComponentName getSearchWidgetProvider() {
1531 SearchManager searchManager =
1532 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1533 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1534 if (searchComponent == null) return null;
1535 return getProviderInPackage(searchComponent.getPackageName());
1536 }
1537
1538 /**
1539 * Gets an appwidget provider from the given package. If the package contains more than
1540 * one appwidget provider, an arbitrary one is returned.
1541 */
1542 private ComponentName getProviderInPackage(String packageName) {
1543 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1544 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1545 if (providers == null) return null;
1546 final int providerCount = providers.size();
1547 for (int i = 0; i < providerCount; i++) {
1548 ComponentName provider = providers.get(i).provider;
1549 if (provider != null && provider.getPackageName().equals(packageName)) {
1550 return provider;
1551 }
1552 }
1553 return null;
1554 }
1555
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001556 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001557 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001558 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001559 }
1560
1561 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001562 ComponentName cn = new ComponentName("com.android.alarmclock",
1563 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001564 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001565 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001566
Winson Chungb3302ae2012-05-01 10:19:14 -07001567 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1568 SQLiteDatabase db, ContentValues values, TypedArray a,
1569 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001570
Mike Cleronb87bd162009-10-30 16:36:56 -07001571 String packageName = a.getString(R.styleable.Favorite_packageName);
1572 String className = a.getString(R.styleable.Favorite_className);
1573
1574 if (packageName == null || className == null) {
1575 return false;
1576 }
Romain Guy693599f2010-03-23 10:58:18 -07001577
1578 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001579 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001580 try {
1581 packageManager.getReceiverInfo(cn, 0);
1582 } catch (Exception e) {
1583 String[] packages = packageManager.currentToCanonicalPackageNames(
1584 new String[] { packageName });
1585 cn = new ComponentName(packages[0], className);
1586 try {
1587 packageManager.getReceiverInfo(cn, 0);
1588 } catch (Exception e1) {
1589 hasPackage = false;
1590 }
1591 }
1592
1593 if (hasPackage) {
1594 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1595 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001596
1597 // Read the extras
1598 Bundle extras = new Bundle();
1599 int widgetDepth = parser.getDepth();
1600 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1601 parser.getDepth() > widgetDepth) {
1602 if (type != XmlPullParser.START_TAG) {
1603 continue;
1604 }
1605
1606 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1607 if (TAG_EXTRA.equals(parser.getName())) {
1608 String key = ar.getString(R.styleable.Extra_key);
1609 String value = ar.getString(R.styleable.Extra_value);
1610 if (key != null && value != null) {
1611 extras.putString(key, value);
1612 } else {
1613 throw new RuntimeException("Widget extras must have a key and value");
1614 }
1615 } else {
1616 throw new RuntimeException("Widgets can contain only extras");
1617 }
1618 ar.recycle();
1619 }
1620
1621 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001622 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001623
Romain Guy693599f2010-03-23 10:58:18 -07001624 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001625 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001626 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001627 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001628 boolean allocatedAppWidgets = false;
1629 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1630
1631 try {
1632 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001633
Mike Cleronb87bd162009-10-30 16:36:56 -07001634 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001635 values.put(Favorites.SPANX, spanX);
1636 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001637 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001638 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001639 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001640 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001641
1642 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001643
Michael Jurka8b805b12012-04-18 14:23:14 -07001644 // TODO: need to check return value
1645 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001646
1647 // Send a broadcast to configure the widget
1648 if (extras != null && !extras.isEmpty()) {
1649 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1650 intent.setComponent(cn);
1651 intent.putExtras(extras);
1652 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1653 mContext.sendBroadcast(intent);
1654 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001655 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001656 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001657 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001658
Mike Cleronb87bd162009-10-30 16:36:56 -07001659 return allocatedAppWidgets;
1660 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001661
1662 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001663 TypedArray a) {
1664 Resources r = mContext.getResources();
1665
1666 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1667 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1668
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001669 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001670 String uri = null;
1671 try {
1672 uri = a.getString(R.styleable.Favorite_uri);
1673 intent = Intent.parseUri(uri, 0);
1674 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001675 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001676 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001677 }
1678
1679 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001680 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001681 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001682 }
1683
Adam Cohendcd297f2013-06-18 13:13:40 -07001684 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001685 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1686 values.put(Favorites.INTENT, intent.toUri(0));
1687 values.put(Favorites.TITLE, r.getString(titleResId));
1688 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1689 values.put(Favorites.SPANX, 1);
1690 values.put(Favorites.SPANY, 1);
1691 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1692 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1693 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001694 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001695
Adam Cohen228da5a2011-07-27 22:23:47 -07001696 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1697 return -1;
1698 }
1699 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001700 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001701
1702 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1703 final ContentResolver resolver = mContext.getContentResolver();
1704 Cursor c = null;
1705 int count = 0;
1706 int curScreen = 0;
1707
1708 try {
1709 c = resolver.query(uri, null, null, null, "title ASC");
1710 } catch (Exception e) {
1711 // Ignore
1712 }
1713
Dan Sandlerd5024042014-01-09 15:01:33 -05001714 // We already have a favorites database in the old provider
1715 if (c != null) {
1716 try {
1717 if (c.getCount() > 0) {
1718 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1719 final int intentIndex
1720 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1721 final int titleIndex
1722 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1723 final int iconTypeIndex
1724 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1725 final int iconIndex
1726 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1727 final int iconPackageIndex
1728 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1729 final int iconResourceIndex
1730 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1731 final int containerIndex
1732 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1733 final int itemTypeIndex
1734 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1735 final int screenIndex
1736 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1737 final int cellXIndex
1738 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1739 final int cellYIndex
1740 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1741 final int uriIndex
1742 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1743 final int displayModeIndex
1744 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1745
1746 int i = 0;
1747 int curX = 0;
1748 int curY = 0;
1749
1750 final LauncherAppState app = LauncherAppState.getInstance();
1751 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1752 final int width = (int) grid.numColumns;
1753 final int height = (int) grid.numRows;
1754 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001755 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001756
1757 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1758
Adam Cohen72960972014-01-15 18:13:55 -08001759 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1760 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001761 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001762
1763 while (c.moveToNext()) {
1764 final int itemType = c.getInt(itemTypeIndex);
1765 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1766 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1767 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1768 continue;
1769 }
1770
1771 final int cellX = c.getInt(cellXIndex);
1772 final int cellY = c.getInt(cellYIndex);
1773 final int screen = c.getInt(screenIndex);
1774 int container = c.getInt(containerIndex);
1775 final String intentStr = c.getString(intentIndex);
1776 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001777 + c.getString(titleIndex) + "\" ("
1778 + cellX + "," + cellY + "@"
1779 + LauncherSettings.Favorites.containerToString(container)
1780 + "/" + screen
1781 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001782
1783 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001784
1785 final Intent intent;
1786 final ComponentName cn;
1787 try {
1788 intent = Intent.parseUri(intentStr, 0);
1789 } catch (URISyntaxException e) {
1790 // bogus intent?
1791 Launcher.addDumpLog(TAG,
1792 "skipping invalid intent uri", true);
1793 continue;
1794 }
1795
1796 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001797 if (TextUtils.isEmpty(intentStr)) {
1798 // no intent? no icon
1799 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1800 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001801 } else if (cn != null &&
1802 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001803 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001804 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001805 "no longer exists.", true);
1806 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001807 } else if (container ==
1808 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1809 // Dedupe icons directly on the workspace
1810
Adam Cohen556f6132014-01-15 15:18:08 -08001811 // Canonicalize
1812 // the Play Store sets the package parameter, but Launcher
1813 // does not, so we clear that out to keep them the same
1814 intent.setPackage(null);
1815 final String key = intent.toUri(0);
1816 if (seenIntents.contains(key)) {
1817 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001818 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001819 } else {
1820 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001821 }
1822 }
1823 }
1824
1825 ContentValues values = new ContentValues(c.getColumnCount());
1826 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1827 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1828 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1829 values.put(LauncherSettings.Favorites.ICON_TYPE,
1830 c.getInt(iconTypeIndex));
1831 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1832 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1833 c.getString(iconPackageIndex));
1834 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1835 c.getString(iconResourceIndex));
1836 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1837 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1838 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1839 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1840 c.getInt(displayModeIndex));
1841
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001842 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1843 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001844 }
1845
1846 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1847 // In a folder or in the hotseat, preserve position
1848 values.put(LauncherSettings.Favorites.SCREEN, screen);
1849 values.put(LauncherSettings.Favorites.CELLX, cellX);
1850 values.put(LauncherSettings.Favorites.CELLY, cellY);
1851 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001852 // For items contained directly on one of the workspace screen,
1853 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001854 }
1855
1856 values.put(LauncherSettings.Favorites.CONTAINER, container);
1857
Adam Cohen72960972014-01-15 18:13:55 -08001858 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1859 shortcuts.add(values);
1860 } else {
1861 folders.add(values);
1862 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001863 }
1864
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001865 // Now that we have all the hotseat icons, let's go through them left-right
1866 // and assign valid locations for them in the new hotseat
1867 final int N = hotseat.size();
1868 for (int idx=0; idx<N; idx++) {
1869 int hotseatX = hotseat.keyAt(idx);
1870 ContentValues values = hotseat.valueAt(idx);
1871
1872 if (hotseatX == grid.hotseatAllAppsRank) {
1873 // let's drop this in the next available hole in the hotseat
1874 while (++hotseatX < hotseatWidth) {
1875 if (hotseat.get(hotseatX) == null) {
1876 // found a spot! move it here
1877 values.put(LauncherSettings.Favorites.SCREEN,
1878 hotseatX);
1879 break;
1880 }
1881 }
1882 }
1883 if (hotseatX >= hotseatWidth) {
1884 // no room for you in the hotseat? it's off to the desktop with you
1885 values.put(LauncherSettings.Favorites.CONTAINER,
1886 Favorites.CONTAINER_DESKTOP);
1887 }
1888 }
1889
Adam Cohen72960972014-01-15 18:13:55 -08001890 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1891 // Folders first
1892 allItems.addAll(folders);
1893 // Then shortcuts
1894 allItems.addAll(shortcuts);
1895
1896 // Layout all the folders
1897 for (ContentValues values: allItems) {
1898 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1899 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1900 // Hotseat items and folder items have already had their
1901 // location information set. Nothing to be done here.
1902 continue;
1903 }
1904 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1905 values.put(LauncherSettings.Favorites.CELLX, curX);
1906 values.put(LauncherSettings.Favorites.CELLY, curY);
1907 curX = (curX + 1) % width;
1908 if (curX == 0) {
1909 curY = (curY + 1);
1910 }
1911 // Leave the last row of icons blank on every screen
1912 if (curY == height - 1) {
1913 curScreen = (int) generateNewScreenId();
1914 curY = 0;
1915 }
1916 }
1917
1918 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001919 db.beginTransaction();
1920 try {
Adam Cohen72960972014-01-15 18:13:55 -08001921 for (ContentValues row: allItems) {
1922 if (row == null) continue;
1923 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001924 < 0) {
1925 return;
1926 } else {
1927 count++;
1928 }
1929 }
1930 db.setTransactionSuccessful();
1931 } finally {
1932 db.endTransaction();
1933 }
1934 }
1935
1936 db.beginTransaction();
1937 try {
1938 for (i=0; i<=curScreen; i++) {
1939 final ContentValues values = new ContentValues();
1940 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1941 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1942 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1943 < 0) {
1944 return;
1945 }
1946 }
1947 db.setTransactionSuccessful();
1948 } finally {
1949 db.endTransaction();
1950 }
1951 }
1952 } finally {
1953 c.close();
1954 }
1955 }
1956
1957 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1958 + (curScreen+1) + " screens", true);
1959
1960 // ensure that new screens are created to hold these icons
1961 setFlagJustLoadedOldDb();
1962
1963 // Update max IDs; very important since we just grabbed IDs from another database
1964 mMaxItemId = initializeMaxItemId(db);
1965 mMaxScreenId = initializeMaxScreenId(db);
1966 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1967 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001968 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001969
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001970 /**
1971 * Build a query string that will match any row where the column matches
1972 * anything in the values list.
1973 */
1974 static String buildOrWhereString(String column, int[] values) {
1975 StringBuilder selectWhere = new StringBuilder();
1976 for (int i = values.length - 1; i >= 0; i--) {
1977 selectWhere.append(column).append("=").append(values[i]);
1978 if (i > 0) {
1979 selectWhere.append(" OR ");
1980 }
1981 }
1982 return selectWhere.toString();
1983 }
1984
1985 static class SqlArguments {
1986 public final String table;
1987 public final String where;
1988 public final String[] args;
1989
1990 SqlArguments(Uri url, String where, String[] args) {
1991 if (url.getPathSegments().size() == 1) {
1992 this.table = url.getPathSegments().get(0);
1993 this.where = where;
1994 this.args = args;
1995 } else if (url.getPathSegments().size() != 2) {
1996 throw new IllegalArgumentException("Invalid URI: " + url);
1997 } else if (!TextUtils.isEmpty(where)) {
1998 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1999 } else {
2000 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002001 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002002 this.args = null;
2003 }
2004 }
2005
2006 SqlArguments(Uri url) {
2007 if (url.getPathSegments().size() == 1) {
2008 table = url.getPathSegments().get(0);
2009 where = null;
2010 args = null;
2011 } else {
2012 throw new IllegalArgumentException("Invalid URI: " + url);
2013 }
2014 }
2015 }
Adam Cohen72960972014-01-15 18:13:55 -08002016}