blob: 39afe10427381602ea7b7f8af45ddbe51670d2e7 [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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Michael Jurkab85f8a42012-04-25 15:48:32 -070030import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080031import android.content.pm.ActivityInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.pm.PackageManager;
33import android.content.res.Resources;
34import android.content.res.TypedArray;
35import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.database.Cursor;
37import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.database.sqlite.SQLiteDatabase;
39import android.database.sqlite.SQLiteOpenHelper;
40import android.database.sqlite.SQLiteQueryBuilder;
41import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080042import android.graphics.Bitmap;
43import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070045import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070046import android.provider.Settings;
47import android.text.TextUtils;
48import android.util.AttributeSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
50import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Chris Wren1ada10d2013-09-13 18:01:38 -040052import com.android.launcher3.LauncherSettings.BaseLauncherColumns;
Daniel Sandler325dc232013-06-05 22:57:57 -040053import com.android.launcher3.LauncherSettings.Favorites;
Michael Jurka8b805b12012-04-18 14:23:14 -070054
55import org.xmlpull.v1.XmlPullParser;
56import org.xmlpull.v1.XmlPullParserException;
57
The Android Open Source Project31dd5032009-03-03 19:32:27 -080058import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070059import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070060import java.util.ArrayList;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000061import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080064 private static final String TAG = "Launcher.LauncherProvider";
65 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
67 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070068
Chris Wren1ada10d2013-09-13 18:01:38 -040069 private static final int DATABASE_VERSION = 15;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Adam Cohene25af792013-06-06 23:08:25 -070071 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Daniel Sandler325dc232013-06-05 22:57:57 -040072 static final String AUTHORITY = "com.android.launcher3.settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070073
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070075 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070077 static final String UPGRADED_FROM_OLD_DATABASE =
78 "UPGRADED_FROM_OLD_DATABASE";
79 static final String EMPTY_DATABASE_CREATED =
80 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020081 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
82 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
Winson Chungb3302ae2012-05-01 10:19:14 -070084 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070085 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070086
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070087 /**
Romain Guy73b979d2009-06-09 12:57:21 -070088 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070089 * {@link AppWidgetHost#deleteHost()} is called during database creation.
90 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
91 */
92 static final Uri CONTENT_APPWIDGET_RESET_URI =
93 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070094
Michael Jurkaa8c760d2011-04-28 14:59:33 -070095 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -070096 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
98 @Override
99 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400100 final Context context = getContext();
101 mOpenHelper = new DatabaseHelper(context);
102 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 return true;
104 }
105
106 @Override
107 public String getType(Uri uri) {
108 SqlArguments args = new SqlArguments(uri, null, null);
109 if (TextUtils.isEmpty(args.where)) {
110 return "vnd.android.cursor.dir/" + args.table;
111 } else {
112 return "vnd.android.cursor.item/" + args.table;
113 }
114 }
115
116 @Override
117 public Cursor query(Uri uri, String[] projection, String selection,
118 String[] selectionArgs, String sortOrder) {
119
120 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
121 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
122 qb.setTables(args.table);
123
Romain Guy73b979d2009-06-09 12:57:21 -0700124 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
126 result.setNotificationUri(getContext().getContentResolver(), uri);
127
128 return result;
129 }
130
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700131 private static long dbInsertAndCheck(DatabaseHelper helper,
132 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
133 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
134 throw new RuntimeException("Error: attempting to add item without specifying an id");
135 }
136 return db.insert(table, nullColumnHack, values);
137 }
138
Adam Cohen228da5a2011-07-27 22:23:47 -0700139 private static void deleteId(SQLiteDatabase db, long id) {
140 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
141 SqlArguments args = new SqlArguments(uri, null, null);
142 db.delete(args.table, args.where, args.args);
143 }
144
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145 @Override
146 public Uri insert(Uri uri, ContentValues initialValues) {
147 SqlArguments args = new SqlArguments(uri);
148
149 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400150 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 if (rowId <= 0) return null;
153
154 uri = ContentUris.withAppendedId(uri, rowId);
155 sendNotify(uri);
156
157 return uri;
158 }
159
160 @Override
161 public int bulkInsert(Uri uri, ContentValues[] values) {
162 SqlArguments args = new SqlArguments(uri);
163
164 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
165 db.beginTransaction();
166 try {
167 int numValues = values.length;
168 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400169 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700170 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
171 return 0;
172 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173 }
174 db.setTransactionSuccessful();
175 } finally {
176 db.endTransaction();
177 }
178
179 sendNotify(uri);
180 return values.length;
181 }
182
183 @Override
184 public int delete(Uri uri, String selection, String[] selectionArgs) {
185 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
186
187 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
188 int count = db.delete(args.table, args.where, args.args);
189 if (count > 0) sendNotify(uri);
190
191 return count;
192 }
193
194 @Override
195 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
196 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
197
Chris Wren1ada10d2013-09-13 18:01:38 -0400198 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
200 int count = db.update(args.table, values, args.where, args.args);
201 if (count > 0) sendNotify(uri);
202
203 return count;
204 }
205
206 private void sendNotify(Uri uri) {
207 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
208 if (notify == null || "true".equals(notify)) {
209 getContext().getContentResolver().notifyChange(uri, null);
210 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400211
212 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400213 LauncherBackupAgentHelper.dataChanged(getContext());
Chris Wren1ada10d2013-09-13 18:01:38 -0400214 }
215
216 private void addModifiedTime(ContentValues values) {
217 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218 }
219
Adam Cohendcd297f2013-06-18 13:13:40 -0700220 public long generateNewItemId() {
221 return mOpenHelper.generateNewItemId();
222 }
223
Winson Chungc763c4e2013-07-19 13:49:06 -0700224 public void updateMaxItemId(long id) {
225 mOpenHelper.updateMaxItemId(id);
226 }
227
Adam Cohendcd297f2013-06-18 13:13:40 -0700228 public long generateNewScreenId() {
229 return mOpenHelper.generateNewScreenId();
230 }
231
232 // This is only required one time while loading the workspace during the
233 // upgrade path, and should never be called from anywhere else.
234 public void updateMaxScreenId(long maxScreenId) {
235 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700236 }
237
Brian Muramatsu5524b492012-10-02 16:55:54 -0700238 /**
Adam Cohene25af792013-06-06 23:08:25 -0700239 * @param Should we load the old db for upgrade? first run only.
240 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700241 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400242 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700243 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
244
Winson Chungc763c4e2013-07-19 13:49:06 -0700245 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700246
Winson Chungc763c4e2013-07-19 13:49:06 -0700247 sJustLoadedFromOldDb = false;
248 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700249
250 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700251 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700252 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700253 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700254 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700255 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700256 }
257
258 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700259 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
260 */
Michael Jurka45355c42012-10-08 13:21:35 +0200261 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400262 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700263 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700264
Winson Chungc763c4e2013-07-19 13:49:06 -0700265 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Michael Jurka45355c42012-10-08 13:21:35 +0200266 int workspaceResId = origWorkspaceResId;
267
Brian Muramatsu5524b492012-10-02 16:55:54 -0700268 // Use default workspace resource if none provided
269 if (workspaceResId == 0) {
Michael Jurka45355c42012-10-08 13:21:35 +0200270 workspaceResId = sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, R.xml.default_workspace);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700271 }
272
Michael Jurkab85f8a42012-04-25 15:48:32 -0700273 // Populate favorites table with initial favorites
274 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700275 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200276 if (origWorkspaceResId != 0) {
277 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
278 }
Adam Cohene25af792013-06-06 23:08:25 -0700279
Brian Muramatsu5524b492012-10-02 16:55:54 -0700280 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700281 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700282 editor.commit();
283 }
284 }
285
Winson Chungc763c4e2013-07-19 13:49:06 -0700286 private static interface ContentValuesCallback {
287 public void onRow(ContentValues values);
288 }
289
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 private static class DatabaseHelper extends SQLiteOpenHelper {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 private static final String TAG_FAVORITES = "favorites";
292 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700293 private static final String TAG_CLOCK = "clock";
294 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700295 private static final String TAG_APPWIDGET = "appwidget";
296 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700297 private static final String TAG_FOLDER = "folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700298 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400299 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700300
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700302 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700303 private long mMaxItemId = -1;
304 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305
306 DatabaseHelper(Context context) {
307 super(context, DATABASE_NAME, null, DATABASE_VERSION);
308 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700309 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700310
311 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
312 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700313 if (mMaxItemId == -1) {
314 mMaxItemId = initializeMaxItemId(getWritableDatabase());
315 }
316 if (mMaxScreenId == -1) {
317 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700318 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800319 }
320
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700321 /**
322 * Send notification that we've deleted the {@link AppWidgetHost},
323 * probably as part of the initial database creation. The receiver may
324 * want to re-call {@link AppWidgetHost#startListening()} to ensure
325 * callbacks are correctly set.
326 */
327 private void sendAppWidgetResetNotify() {
328 final ContentResolver resolver = mContext.getContentResolver();
329 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
330 }
331
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 @Override
333 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800334 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700335
Adam Cohendcd297f2013-06-18 13:13:40 -0700336 mMaxItemId = 1;
337 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700338
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339 db.execSQL("CREATE TABLE favorites (" +
340 "_id INTEGER PRIMARY KEY," +
341 "title TEXT," +
342 "intent TEXT," +
343 "container INTEGER," +
344 "screen INTEGER," +
345 "cellX INTEGER," +
346 "cellY INTEGER," +
347 "spanX INTEGER," +
348 "spanY INTEGER," +
349 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700350 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 "isShortcut INTEGER," +
352 "iconType INTEGER," +
353 "iconPackage TEXT," +
354 "iconResource TEXT," +
355 "icon BLOB," +
356 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400357 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400358 "appWidgetProvider TEXT," +
359 "modified INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700361 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800362
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700363 // Database was just created, so wipe any previous widgets
364 if (mAppWidgetHost != null) {
365 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700366 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700368
Winson Chungc763c4e2013-07-19 13:49:06 -0700369 // Try converting the old database
370 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
371 public void onRow(ContentValues values) {
372 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
373 if (container == Favorites.CONTAINER_DESKTOP) {
374 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
375 screen = (int) upgradeLauncherDb_permuteScreens(screen);
376 values.put(LauncherSettings.Favorites.SCREEN, screen);
377 }
378 }
379 };
380 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
381 "/old_favorites?notify=true");
382 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
383 // Try and upgrade from the Launcher2 db
384 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
385 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
386 // If we fail, then set a flag to load the default workspace
387 setFlagEmptyDbCreated();
388 return;
389 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800390 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700391 // Right now, in non-default workspace cases, we want to run the final
392 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
393 // set that flag too.
394 setFlagJustLoadedOldDb();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 }
396
Adam Cohendcd297f2013-06-18 13:13:40 -0700397 private void addWorkspacesTable(SQLiteDatabase db) {
398 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
399 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400400 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
401 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700402 ");");
403 }
404
Winson Chungc763c4e2013-07-19 13:49:06 -0700405 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400406 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700407 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
408 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700409 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
410 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700411 editor.commit();
412 }
413
Winson Chungc763c4e2013-07-19 13:49:06 -0700414 private void setFlagEmptyDbCreated() {
415 String spKey = LauncherAppState.getSharedPreferencesKey();
416 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
417 SharedPreferences.Editor editor = sp.edit();
418 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
419 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
420 editor.commit();
421 }
422
423 // We rearrange the screens from the old launcher
424 // 12345 -> 34512
425 private long upgradeLauncherDb_permuteScreens(long screen) {
426 if (screen >= 2) {
427 return screen - 2;
428 } else {
429 return screen + 3;
430 }
431 }
432
433 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
434 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800435 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800436 boolean converted = false;
437
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438 final ContentResolver resolver = mContext.getContentResolver();
439 Cursor cursor = null;
440
441 try {
442 cursor = resolver.query(uri, null, null, null, null);
443 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700444 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800445 }
446
447 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700448 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800449 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700450 if (cursor.getCount() > 0) {
451 converted = copyFromCursor(db, cursor, cb) > 0;
452 if (converted && deleteRows) {
453 resolver.delete(uri, null, null);
454 }
455 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800456 } finally {
457 cursor.close();
458 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800459 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700460
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800461 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700462 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800463 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800464 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700465
466 // Update max item id
467 mMaxItemId = initializeMaxItemId(db);
468 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 }
470
471 return converted;
472 }
473
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700475 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800476 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
477 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
478 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
479 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
480 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
481 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
482 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
483 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
484 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
485 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
486 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
487 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
488 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
489
490 ContentValues[] rows = new ContentValues[c.getCount()];
491 int i = 0;
492 while (c.moveToNext()) {
493 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700494 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800495 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
496 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
497 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
498 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
499 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
500 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
501 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
502 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700503 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800504 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
505 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
506 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
507 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
508 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700509 if (cb != null) {
510 cb.onRow(values);
511 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800512 rows[i++] = values;
513 }
514
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800515 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700516 if (i > 0) {
517 db.beginTransaction();
518 try {
519 int numValues = rows.length;
520 for (i = 0; i < numValues; i++) {
521 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
522 return 0;
523 } else {
524 total++;
525 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800526 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700527 db.setTransactionSuccessful();
528 } finally {
529 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800531 }
532
533 return total;
534 }
535
536 @Override
537 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700538 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700539
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700541 if (version < 3) {
542 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800543 db.beginTransaction();
544 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700545 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700547 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700549 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550 } catch (SQLException ex) {
551 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800552 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800553 } finally {
554 db.endTransaction();
555 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700556
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800557 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700558 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 convertWidgets(db);
560 }
561 }
Romain Guy73b979d2009-06-09 12:57:21 -0700562
563 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800564 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700565 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700566
Romain Guy509cd6a2010-03-23 15:10:56 -0700567 // Where's version 5?
568 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400569 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700570 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
571 // but version 5 on there was the updateContactsShortcuts change
572 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
573 // The updateContactsShortcuts change is idempotent, so running it twice
574 // is okay so we'll do that when upgrading the devices that shipped with it.
575 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800576 // We went from 3 to 5 screens. Move everything 1 to the right
577 db.beginTransaction();
578 try {
579 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
580 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800581 } catch (SQLException ex) {
582 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800583 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800584 } finally {
585 db.endTransaction();
586 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700587
Romain Guy509cd6a2010-03-23 15:10:56 -0700588 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800589 if (updateContactsShortcuts(db)) {
590 version = 6;
591 }
592 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000593
594 if (version < 7) {
595 // Version 7 gets rid of the special search widget.
596 convertWidgets(db);
597 version = 7;
598 }
599
Joe Onorato0589f0f2010-02-08 13:44:00 -0800600 if (version < 8) {
601 // Version 8 (froyo) has the icons all normalized. This should
602 // already be the case in practice, but we now rely on it and don't
603 // resample the images each time.
604 normalizeIcons(db);
605 version = 8;
606 }
607
Winson Chung3d503fb2011-07-13 17:25:49 -0700608 if (version < 9) {
609 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
610 // 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 -0700611 if (mMaxItemId == -1) {
612 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700613 }
614
615 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800616 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700617 version = 9;
618 }
619
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700620 // We bumped the version three time during JB, once to update the launch flags, once to
621 // update the override for the default launch animation and once to set the mimetype
622 // to improve startup performance
623 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700624 // Contact shortcuts need a different set of flags to be launched now
625 // The updateContactsShortcuts change is idempotent, so we can keep using it like
626 // back in the Donut days
627 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700628 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700629 }
630
Adam Cohendcd297f2013-06-18 13:13:40 -0700631 if (version < 13) {
632 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
633 // to persist workspace screens and their relative order.
634 mMaxScreenId = 0;
635
636 // This will never happen in the wild, but when we switch to using workspace
637 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700638 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700639
640 addWorkspacesTable(db);
641 version = 13;
642 }
643
Chris Wrend5e66bf2013-09-16 14:02:29 -0400644 if (version < 14) {
645 db.beginTransaction();
646 try {
647 // Insert new column for holding widget provider name
648 db.execSQL("ALTER TABLE favorites " +
649 "ADD COLUMN appWidgetProvider TEXT;");
650 db.setTransactionSuccessful();
651 version = 14;
652 } catch (SQLException ex) {
653 // Old version remains, which means we wipe old data
654 Log.e(TAG, ex.getMessage(), ex);
655 } finally {
656 db.endTransaction();
657 }
658 }
659
Chris Wren1ada10d2013-09-13 18:01:38 -0400660
661 if (version < 15) {
662 db.beginTransaction();
663 try {
664 // Insert new column for holding update timestamp
665 db.execSQL("ALTER TABLE favorites " +
666 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
667 db.execSQL("ALTER TABLE workspaceScreens " +
668 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
669 db.setTransactionSuccessful();
670 version = 15;
671 } catch (SQLException ex) {
672 // Old version remains, which means we wipe old data
673 Log.e(TAG, ex.getMessage(), ex);
674 } finally {
675 db.endTransaction();
676 }
677 }
678
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800680 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700682 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
683
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 onCreate(db);
685 }
686 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800687
688 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800689 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
690 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
691
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700692 Cursor c = null;
693 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800694 db.beginTransaction();
695 try {
696 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700697 c = db.query(TABLE_FAVORITES,
698 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800699 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700700 if (c == null) return false;
701
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800702 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700703
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800704 final int idIndex = c.getColumnIndex(Favorites._ID);
705 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700706
707 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800708 long favoriteId = c.getLong(idIndex);
709 final String intentUri = c.getString(intentIndex);
710 if (intentUri != null) {
711 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700712 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800713 android.util.Log.d("Home", intent.toString());
714 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700715 if (uri != null) {
716 final String data = uri.toString();
717 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
718 actionQuickContact.equals(intent.getAction())) &&
719 (data.startsWith("content://contacts/people/") ||
720 data.startsWith("content://com.android.contacts/" +
721 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800722
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700723 final Intent newIntent = new Intent(actionQuickContact);
724 // When starting from the launcher, start in a new, cleared task
725 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
726 // clear the whole thing preemptively here since
727 // QuickContactActivity will finish itself when launching other
728 // detail activities.
729 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
730 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700731 newIntent.putExtra(
732 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700733 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700734 // Determine the type and also put that in the shortcut
735 // (that can speed up launch a bit)
736 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800737
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700738 final ContentValues values = new ContentValues();
739 values.put(LauncherSettings.Favorites.INTENT,
740 newIntent.toUri(0));
741
742 String updateWhere = Favorites._ID + "=" + favoriteId;
743 db.update(TABLE_FAVORITES, values, updateWhere, null);
744 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800745 }
746 } catch (RuntimeException ex) {
747 Log.e(TAG, "Problem upgrading shortcut", ex);
748 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700749 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800750 }
751 }
752 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700753
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800754 db.setTransactionSuccessful();
755 } catch (SQLException ex) {
756 Log.w(TAG, "Problem while upgrading contacts", ex);
757 return false;
758 } finally {
759 db.endTransaction();
760 if (c != null) {
761 c.close();
762 }
763 }
764
765 return true;
766 }
767
Joe Onorato0589f0f2010-02-08 13:44:00 -0800768 private void normalizeIcons(SQLiteDatabase db) {
769 Log.d(TAG, "normalizing icons");
770
Joe Onorato346e1292010-02-18 10:34:24 -0500771 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800772 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400773 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800774 try {
775 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400776 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600777 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800778
779 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
780 Favorites.ICON_TYPE_BITMAP, null);
781
782 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
783 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
784
785 while (c.moveToNext()) {
786 long id = c.getLong(idIndex);
787 byte[] data = c.getBlob(iconIndex);
788 try {
789 Bitmap bitmap = Utilities.resampleIconBitmap(
790 BitmapFactory.decodeByteArray(data, 0, data.length),
791 mContext);
792 if (bitmap != null) {
793 update.bindLong(1, id);
794 data = ItemInfo.flattenBitmap(bitmap);
795 if (data != null) {
796 update.bindBlob(2, data);
797 update.execute();
798 }
799 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800800 }
801 } catch (Exception e) {
802 if (!logged) {
803 Log.e(TAG, "Failed normalizing icon " + id, e);
804 } else {
805 Log.e(TAG, "Also failed normalizing icon " + id);
806 }
807 logged = true;
808 }
809 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000810 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800811 } catch (SQLException ex) {
812 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
813 } finally {
814 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400815 if (update != null) {
816 update.close();
817 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800818 if (c != null) {
819 c.close();
820 }
821 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700822 }
823
824 // Generates a new ID to use for an object in your database. This method should be only
825 // called from the main UI thread. As an exception, we do call it when we call the
826 // constructor from the worker thread; however, this doesn't extend until after the
827 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
828 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700829 public long generateNewItemId() {
830 if (mMaxItemId < 0) {
831 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700832 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700833 mMaxItemId += 1;
834 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700835 }
836
Winson Chungc763c4e2013-07-19 13:49:06 -0700837 public void updateMaxItemId(long id) {
838 mMaxItemId = id + 1;
839 }
840
Adam Cohendcd297f2013-06-18 13:13:40 -0700841 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700842 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
843
844 // get the result
845 final int maxIdIndex = 0;
846 long id = -1;
847 if (c != null && c.moveToNext()) {
848 id = c.getLong(maxIdIndex);
849 }
Michael Jurka5130e402011-10-13 04:55:35 -0700850 if (c != null) {
851 c.close();
852 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700853
854 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700855 throw new RuntimeException("Error: could not query max item id");
856 }
857
858 return id;
859 }
860
861 // Generates a new ID to use for an workspace screen in your database. This method
862 // should be only called from the main UI thread. As an exception, we do call it when we
863 // call the constructor from the worker thread; however, this doesn't extend until after the
864 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
865 // after that point
866 public long generateNewScreenId() {
867 if (mMaxScreenId < 0) {
868 throw new RuntimeException("Error: max screen id was not initialized");
869 }
870 mMaxScreenId += 1;
871 return mMaxScreenId;
872 }
873
874 public void updateMaxScreenId(long maxScreenId) {
875 mMaxScreenId = maxScreenId;
876 }
877
878 private long initializeMaxScreenId(SQLiteDatabase db) {
879 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
880
881 // get the result
882 final int maxIdIndex = 0;
883 long id = -1;
884 if (c != null && c.moveToNext()) {
885 id = c.getLong(maxIdIndex);
886 }
887 if (c != null) {
888 c.close();
889 }
890
891 if (id == -1) {
892 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700893 }
894
895 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800896 }
897
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800898 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700899 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +0000900 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800901 */
902 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +0000903 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800904 final int[] bindSources = new int[] {
905 Favorites.ITEM_TYPE_WIDGET_CLOCK,
906 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +0000907 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800908 };
Bjorn Bringert7984c942009-12-09 15:38:25 +0000909
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800910 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700911
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800912 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700913
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800914 db.beginTransaction();
915 try {
916 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +0000917 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800918 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700919
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800920 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700921
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800922 final ContentValues values = new ContentValues();
923 while (c != null && c.moveToNext()) {
924 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +0000925 int favoriteType = c.getInt(1);
926
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700927 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700929 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700930
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800931 if (LOGD) {
932 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
933 + " for favoriteId=" + favoriteId);
934 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800935 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +0000936 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
937 values.put(Favorites.APPWIDGET_ID, appWidgetId);
938
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800939 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +0000940 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
941 values.put(LauncherSettings.Favorites.SPANX, 4);
942 values.put(LauncherSettings.Favorites.SPANY, 1);
943 } else {
944 values.put(LauncherSettings.Favorites.SPANX, 2);
945 values.put(LauncherSettings.Favorites.SPANY, 2);
946 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800947
948 String updateWhere = Favorites._ID + "=" + favoriteId;
949 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +0000950
Bjorn Bringert34251342009-12-15 13:33:11 +0000951 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700952 // TODO: check return value
953 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000954 new ComponentName("com.android.alarmclock",
955 "com.android.alarmclock.AnalogAppWidgetProvider"));
956 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700957 // TODO: check return value
958 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000959 new ComponentName("com.android.camera",
960 "com.android.camera.PhotoAppWidgetProvider"));
961 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700962 // TODO: check return value
963 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +0000964 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +0000965 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800967 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800968 }
969 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700970
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800971 db.setTransactionSuccessful();
972 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800973 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800974 } finally {
975 db.endTransaction();
976 if (c != null) {
977 c.close();
978 }
979 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700980
981 // Update max item id
982 mMaxItemId = initializeMaxItemId(db);
983 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800984 }
985
Michael Jurka8b805b12012-04-18 14:23:14 -0700986 private static final void beginDocument(XmlPullParser parser, String firstElementName)
987 throws XmlPullParserException, IOException {
988 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -0700989 while ((type = parser.next()) != XmlPullParser.START_TAG
990 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700991 ;
992 }
993
Michael Jurka9bc8eba2012-05-21 20:36:44 -0700994 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700995 throw new XmlPullParserException("No start tag found");
996 }
997
998 if (!parser.getName().equals(firstElementName)) {
999 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1000 ", expected " + firstElementName);
1001 }
1002 }
1003
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001004 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001005 * Loads the default set of favorite packages from an xml file.
1006 *
1007 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001008 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001009 */
Winson Chung6d092682011-11-16 18:43:26 -08001010 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001011 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1012 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1013 ContentValues values = new ContentValues();
1014
Daniel Sandler57dac262013-10-03 13:28:36 -04001015 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1016
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001017 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001018 int i = 0;
1019 try {
Winson Chung6d092682011-11-16 18:43:26 -08001020 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001021 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001022 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001023
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001024 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001025
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001026 int type;
1027 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1028 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1029
1030 if (type != XmlPullParser.START_TAG) {
1031 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001032 }
1033
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001034 boolean added = false;
1035 final String name = parser.getName();
1036
Daniel Sandler57dac262013-10-03 13:28:36 -04001037 if (TAG_INCLUDE.equals(name)) {
1038 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1039
1040 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1041
1042 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1043 "", resId));
1044
1045 if (resId != 0 && resId != workspaceResourceId) {
1046 // recursively load some more favorites, why not?
1047 i += loadFavorites(db, resId);
1048 added = false;
1049 mMaxItemId = -1;
1050 } else {
1051 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1052 }
1053
1054 a.recycle();
1055
1056 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1057 continue;
1058 }
1059
1060 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001061 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1062
Winson Chung3d503fb2011-07-13 17:25:49 -07001063 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1064 if (a.hasValue(R.styleable.Favorite_container)) {
1065 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1066 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001067
Winson Chung6d092682011-11-16 18:43:26 -08001068 String screen = a.getString(R.styleable.Favorite_screen);
1069 String x = a.getString(R.styleable.Favorite_x);
1070 String y = a.getString(R.styleable.Favorite_y);
1071
Winson Chung6d092682011-11-16 18:43:26 -08001072 values.clear();
1073 values.put(LauncherSettings.Favorites.CONTAINER, container);
1074 values.put(LauncherSettings.Favorites.SCREEN, screen);
1075 values.put(LauncherSettings.Favorites.CELLX, x);
1076 values.put(LauncherSettings.Favorites.CELLY, y);
1077
Daniel Sandler57dac262013-10-03 13:28:36 -04001078 if (LOGD) {
1079 final String title = a.getString(R.styleable.Favorite_title);
1080 final String pkg = a.getString(R.styleable.Favorite_packageName);
1081 final String something = title != null ? title : pkg;
1082 Log.v(TAG, String.format(
1083 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1084 "", name,
1085 (something == null ? "" : (" \"" + something + "\"")),
1086 container, screen, x, y));
1087 }
1088
Winson Chung6d092682011-11-16 18:43:26 -08001089 if (TAG_FAVORITE.equals(name)) {
1090 long id = addAppShortcut(db, values, a, packageManager, intent);
1091 added = id >= 0;
1092 } else if (TAG_SEARCH.equals(name)) {
1093 added = addSearchWidget(db, values);
1094 } else if (TAG_CLOCK.equals(name)) {
1095 added = addClockWidget(db, values);
1096 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001097 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001098 } else if (TAG_SHORTCUT.equals(name)) {
1099 long id = addUriShortcut(db, values, a);
1100 added = id >= 0;
1101 } else if (TAG_FOLDER.equals(name)) {
1102 String title;
1103 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1104 if (titleResId != -1) {
1105 title = mContext.getResources().getString(titleResId);
1106 } else {
1107 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001108 }
Winson Chung6d092682011-11-16 18:43:26 -08001109 values.put(LauncherSettings.Favorites.TITLE, title);
1110 long folderId = addFolder(db, values);
1111 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001112
Winson Chung6d092682011-11-16 18:43:26 -08001113 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001114
Winson Chung6d092682011-11-16 18:43:26 -08001115 int folderDepth = parser.getDepth();
1116 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1117 parser.getDepth() > folderDepth) {
1118 if (type != XmlPullParser.START_TAG) {
1119 continue;
1120 }
1121 final String folder_item_name = parser.getName();
1122
1123 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1124 R.styleable.Favorite);
1125 values.clear();
1126 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1127
Daniel Sandler57dac262013-10-03 13:28:36 -04001128 if (LOGD) {
1129 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1130 final String uri = ar.getString(R.styleable.Favorite_uri);
1131 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1132 folder_item_name, uri != null ? uri : pkg));
1133 }
1134
Winson Chung6d092682011-11-16 18:43:26 -08001135 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1136 long id =
1137 addAppShortcut(db, values, ar, packageManager, intent);
1138 if (id >= 0) {
1139 folderItems.add(id);
1140 }
1141 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1142 long id = addUriShortcut(db, values, ar);
1143 if (id >= 0) {
1144 folderItems.add(id);
1145 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001146 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001147 throw new RuntimeException("Folders can " +
1148 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001149 }
Winson Chung6d092682011-11-16 18:43:26 -08001150 ar.recycle();
1151 }
1152 // We can only have folders with >= 2 items, so we need to remove the
1153 // folder and clean up if less than 2 items were included, or some
1154 // failed to add, and less than 2 were actually added
1155 if (folderItems.size() < 2 && folderId >= 0) {
1156 // We just delete the folder and any items that made it
1157 deleteId(db, folderId);
1158 if (folderItems.size() > 0) {
1159 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001160 }
Winson Chung6d092682011-11-16 18:43:26 -08001161 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001162 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001163 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001164 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001165 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001166 }
1167 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001168 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001169 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001170 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001171 } catch (RuntimeException e) {
1172 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001173 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001174
Winson Chungc763c4e2013-07-19 13:49:06 -07001175 // Update the max item id after we have loaded the database
1176 if (mMaxItemId == -1) {
1177 mMaxItemId = initializeMaxItemId(db);
1178 }
1179
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001180 return i;
1181 }
1182
Adam Cohen228da5a2011-07-27 22:23:47 -07001183 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001184 PackageManager packageManager, Intent intent) {
Adam Cohen228da5a2011-07-27 22:23:47 -07001185 long id = -1;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001186 ActivityInfo info;
1187 String packageName = a.getString(R.styleable.Favorite_packageName);
1188 String className = a.getString(R.styleable.Favorite_className);
1189 try {
Romain Guy693599f2010-03-23 10:58:18 -07001190 ComponentName cn;
1191 try {
1192 cn = new ComponentName(packageName, className);
1193 info = packageManager.getActivityInfo(cn, 0);
1194 } catch (PackageManager.NameNotFoundException nnfe) {
1195 String[] packages = packageManager.currentToCanonicalPackageNames(
1196 new String[] { packageName });
1197 cn = new ComponentName(packages[0], className);
1198 info = packageManager.getActivityInfo(cn, 0);
1199 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001200 id = generateNewItemId();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001201 intent.setComponent(cn);
Romain Guy693599f2010-03-23 10:58:18 -07001202 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1203 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Romain Guy1ce1a242009-06-23 17:34:54 -07001204 values.put(Favorites.INTENT, intent.toUri(0));
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001205 values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
1206 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1207 values.put(Favorites.SPANX, 1);
1208 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001209 values.put(Favorites._ID, generateNewItemId());
Adam Cohen228da5a2011-07-27 22:23:47 -07001210 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1211 return -1;
1212 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001213 } catch (PackageManager.NameNotFoundException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001214 Log.w(TAG, "Unable to add favorite: " + packageName +
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001215 "/" + className, e);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001216 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001217 return id;
1218 }
1219
1220 private long addFolder(SQLiteDatabase db, ContentValues values) {
1221 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1222 values.put(Favorites.SPANX, 1);
1223 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001224 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001225 values.put(Favorites._ID, id);
1226 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1227 return -1;
1228 } else {
1229 return id;
1230 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001231 }
1232
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001233 private ComponentName getSearchWidgetProvider() {
1234 SearchManager searchManager =
1235 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1236 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1237 if (searchComponent == null) return null;
1238 return getProviderInPackage(searchComponent.getPackageName());
1239 }
1240
1241 /**
1242 * Gets an appwidget provider from the given package. If the package contains more than
1243 * one appwidget provider, an arbitrary one is returned.
1244 */
1245 private ComponentName getProviderInPackage(String packageName) {
1246 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1247 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1248 if (providers == null) return null;
1249 final int providerCount = providers.size();
1250 for (int i = 0; i < providerCount; i++) {
1251 ComponentName provider = providers.get(i).provider;
1252 if (provider != null && provider.getPackageName().equals(packageName)) {
1253 return provider;
1254 }
1255 }
1256 return null;
1257 }
1258
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001259 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001260 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001261 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001262 }
1263
1264 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001265 ComponentName cn = new ComponentName("com.android.alarmclock",
1266 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001267 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001268 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001269
Winson Chungb3302ae2012-05-01 10:19:14 -07001270 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1271 SQLiteDatabase db, ContentValues values, TypedArray a,
1272 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001273
Mike Cleronb87bd162009-10-30 16:36:56 -07001274 String packageName = a.getString(R.styleable.Favorite_packageName);
1275 String className = a.getString(R.styleable.Favorite_className);
1276
1277 if (packageName == null || className == null) {
1278 return false;
1279 }
Romain Guy693599f2010-03-23 10:58:18 -07001280
1281 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001282 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001283 try {
1284 packageManager.getReceiverInfo(cn, 0);
1285 } catch (Exception e) {
1286 String[] packages = packageManager.currentToCanonicalPackageNames(
1287 new String[] { packageName });
1288 cn = new ComponentName(packages[0], className);
1289 try {
1290 packageManager.getReceiverInfo(cn, 0);
1291 } catch (Exception e1) {
1292 hasPackage = false;
1293 }
1294 }
1295
1296 if (hasPackage) {
1297 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1298 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001299
1300 // Read the extras
1301 Bundle extras = new Bundle();
1302 int widgetDepth = parser.getDepth();
1303 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1304 parser.getDepth() > widgetDepth) {
1305 if (type != XmlPullParser.START_TAG) {
1306 continue;
1307 }
1308
1309 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1310 if (TAG_EXTRA.equals(parser.getName())) {
1311 String key = ar.getString(R.styleable.Extra_key);
1312 String value = ar.getString(R.styleable.Extra_value);
1313 if (key != null && value != null) {
1314 extras.putString(key, value);
1315 } else {
1316 throw new RuntimeException("Widget extras must have a key and value");
1317 }
1318 } else {
1319 throw new RuntimeException("Widgets can contain only extras");
1320 }
1321 ar.recycle();
1322 }
1323
1324 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001325 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001326
Romain Guy693599f2010-03-23 10:58:18 -07001327 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001328 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001329 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001330 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001331 boolean allocatedAppWidgets = false;
1332 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1333
1334 try {
1335 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001336
Mike Cleronb87bd162009-10-30 16:36:56 -07001337 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001338 values.put(Favorites.SPANX, spanX);
1339 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001340 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001341 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001342 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001343 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001344
1345 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001346
Michael Jurka8b805b12012-04-18 14:23:14 -07001347 // TODO: need to check return value
1348 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001349
1350 // Send a broadcast to configure the widget
1351 if (extras != null && !extras.isEmpty()) {
1352 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1353 intent.setComponent(cn);
1354 intent.putExtras(extras);
1355 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1356 mContext.sendBroadcast(intent);
1357 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001358 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001359 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001360 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001361
Mike Cleronb87bd162009-10-30 16:36:56 -07001362 return allocatedAppWidgets;
1363 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001364
1365 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001366 TypedArray a) {
1367 Resources r = mContext.getResources();
1368
1369 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1370 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1371
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001372 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001373 String uri = null;
1374 try {
1375 uri = a.getString(R.styleable.Favorite_uri);
1376 intent = Intent.parseUri(uri, 0);
1377 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001378 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001379 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001380 }
1381
1382 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001383 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001384 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001385 }
1386
Adam Cohendcd297f2013-06-18 13:13:40 -07001387 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001388 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1389 values.put(Favorites.INTENT, intent.toUri(0));
1390 values.put(Favorites.TITLE, r.getString(titleResId));
1391 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1392 values.put(Favorites.SPANX, 1);
1393 values.put(Favorites.SPANY, 1);
1394 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1395 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1396 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001397 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001398
Adam Cohen228da5a2011-07-27 22:23:47 -07001399 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1400 return -1;
1401 }
1402 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001403 }
1404 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001405
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001406 /**
1407 * Build a query string that will match any row where the column matches
1408 * anything in the values list.
1409 */
1410 static String buildOrWhereString(String column, int[] values) {
1411 StringBuilder selectWhere = new StringBuilder();
1412 for (int i = values.length - 1; i >= 0; i--) {
1413 selectWhere.append(column).append("=").append(values[i]);
1414 if (i > 0) {
1415 selectWhere.append(" OR ");
1416 }
1417 }
1418 return selectWhere.toString();
1419 }
1420
1421 static class SqlArguments {
1422 public final String table;
1423 public final String where;
1424 public final String[] args;
1425
1426 SqlArguments(Uri url, String where, String[] args) {
1427 if (url.getPathSegments().size() == 1) {
1428 this.table = url.getPathSegments().get(0);
1429 this.where = where;
1430 this.args = args;
1431 } else if (url.getPathSegments().size() != 2) {
1432 throw new IllegalArgumentException("Invalid URI: " + url);
1433 } else if (!TextUtils.isEmpty(where)) {
1434 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1435 } else {
1436 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001437 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001438 this.args = null;
1439 }
1440 }
1441
1442 SqlArguments(Uri url) {
1443 if (url.getPathSegments().size() == 1) {
1444 table = url.getPathSegments().get(0);
1445 where = null;
1446 args = null;
1447 } else {
1448 throw new IllegalArgumentException("Invalid URI: " + url);
1449 }
1450 }
1451 }
1452}