blob: 471d2d2fcf91ec4295816f0b93ee156a3ba00d30 [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
213 LauncherBackupAgent.dataChanged(getContext());
214 }
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";
Winson Chung3d503fb2011-07-13 17:25:49 -0700299
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700301 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700302 private long mMaxItemId = -1;
303 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304
305 DatabaseHelper(Context context) {
306 super(context, DATABASE_NAME, null, DATABASE_VERSION);
307 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700308 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700309
310 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
311 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700312 if (mMaxItemId == -1) {
313 mMaxItemId = initializeMaxItemId(getWritableDatabase());
314 }
315 if (mMaxScreenId == -1) {
316 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700317 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318 }
319
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700320 /**
321 * Send notification that we've deleted the {@link AppWidgetHost},
322 * probably as part of the initial database creation. The receiver may
323 * want to re-call {@link AppWidgetHost#startListening()} to ensure
324 * callbacks are correctly set.
325 */
326 private void sendAppWidgetResetNotify() {
327 final ContentResolver resolver = mContext.getContentResolver();
328 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
329 }
330
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 @Override
332 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800333 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700334
Adam Cohendcd297f2013-06-18 13:13:40 -0700335 mMaxItemId = 1;
336 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700337
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338 db.execSQL("CREATE TABLE favorites (" +
339 "_id INTEGER PRIMARY KEY," +
340 "title TEXT," +
341 "intent TEXT," +
342 "container INTEGER," +
343 "screen INTEGER," +
344 "cellX INTEGER," +
345 "cellY INTEGER," +
346 "spanX INTEGER," +
347 "spanY INTEGER," +
348 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700349 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 "isShortcut INTEGER," +
351 "iconType INTEGER," +
352 "iconPackage TEXT," +
353 "iconResource TEXT," +
354 "icon BLOB," +
355 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400356 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400357 "appWidgetProvider TEXT," +
358 "modified INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700360 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800361
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700362 // Database was just created, so wipe any previous widgets
363 if (mAppWidgetHost != null) {
364 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700365 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800366 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700367
Winson Chungc763c4e2013-07-19 13:49:06 -0700368 // Try converting the old database
369 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
370 public void onRow(ContentValues values) {
371 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
372 if (container == Favorites.CONTAINER_DESKTOP) {
373 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
374 screen = (int) upgradeLauncherDb_permuteScreens(screen);
375 values.put(LauncherSettings.Favorites.SCREEN, screen);
376 }
377 }
378 };
379 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
380 "/old_favorites?notify=true");
381 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
382 // Try and upgrade from the Launcher2 db
383 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
384 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
385 // If we fail, then set a flag to load the default workspace
386 setFlagEmptyDbCreated();
387 return;
388 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700390 // Right now, in non-default workspace cases, we want to run the final
391 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
392 // set that flag too.
393 setFlagJustLoadedOldDb();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 }
395
Adam Cohendcd297f2013-06-18 13:13:40 -0700396 private void addWorkspacesTable(SQLiteDatabase db) {
397 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
398 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400399 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
400 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700401 ");");
402 }
403
Winson Chungc763c4e2013-07-19 13:49:06 -0700404 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400405 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700406 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
407 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700408 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
409 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700410 editor.commit();
411 }
412
Winson Chungc763c4e2013-07-19 13:49:06 -0700413 private void setFlagEmptyDbCreated() {
414 String spKey = LauncherAppState.getSharedPreferencesKey();
415 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
416 SharedPreferences.Editor editor = sp.edit();
417 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
418 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
419 editor.commit();
420 }
421
422 // We rearrange the screens from the old launcher
423 // 12345 -> 34512
424 private long upgradeLauncherDb_permuteScreens(long screen) {
425 if (screen >= 2) {
426 return screen - 2;
427 } else {
428 return screen + 3;
429 }
430 }
431
432 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
433 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800434 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800435 boolean converted = false;
436
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800437 final ContentResolver resolver = mContext.getContentResolver();
438 Cursor cursor = null;
439
440 try {
441 cursor = resolver.query(uri, null, null, null, null);
442 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700443 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800444 }
445
446 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700447 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800448 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700449 if (cursor.getCount() > 0) {
450 converted = copyFromCursor(db, cursor, cb) > 0;
451 if (converted && deleteRows) {
452 resolver.delete(uri, null, null);
453 }
454 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800455 } finally {
456 cursor.close();
457 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800458 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700459
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800460 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700461 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800462 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700464
465 // Update max item id
466 mMaxItemId = initializeMaxItemId(db);
467 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 }
469
470 return converted;
471 }
472
Winson Chungc763c4e2013-07-19 13:49:06 -0700473 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700474 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800475 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
476 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
477 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
478 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
479 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
480 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
481 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
482 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
483 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
484 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
485 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
486 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
487 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
488
489 ContentValues[] rows = new ContentValues[c.getCount()];
490 int i = 0;
491 while (c.moveToNext()) {
492 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700493 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
495 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
496 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
497 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
498 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
499 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
500 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
501 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700502 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800503 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
504 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
505 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
506 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
507 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700508 if (cb != null) {
509 cb.onRow(values);
510 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800511 rows[i++] = values;
512 }
513
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800514 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700515 if (i > 0) {
516 db.beginTransaction();
517 try {
518 int numValues = rows.length;
519 for (i = 0; i < numValues; i++) {
520 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
521 return 0;
522 } else {
523 total++;
524 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800525 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700526 db.setTransactionSuccessful();
527 } finally {
528 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800529 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 }
531
532 return total;
533 }
534
535 @Override
536 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700537 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700538
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800539 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700540 if (version < 3) {
541 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 db.beginTransaction();
543 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700544 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700546 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800547 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700548 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549 } catch (SQLException ex) {
550 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800551 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552 } finally {
553 db.endTransaction();
554 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700555
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800556 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700557 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800558 convertWidgets(db);
559 }
560 }
Romain Guy73b979d2009-06-09 12:57:21 -0700561
562 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800563 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700564 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700565
Romain Guy509cd6a2010-03-23 15:10:56 -0700566 // Where's version 5?
567 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400568 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700569 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
570 // but version 5 on there was the updateContactsShortcuts change
571 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
572 // The updateContactsShortcuts change is idempotent, so running it twice
573 // is okay so we'll do that when upgrading the devices that shipped with it.
574 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800575 // We went from 3 to 5 screens. Move everything 1 to the right
576 db.beginTransaction();
577 try {
578 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
579 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800580 } catch (SQLException ex) {
581 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800582 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800583 } finally {
584 db.endTransaction();
585 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700586
Romain Guy509cd6a2010-03-23 15:10:56 -0700587 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800588 if (updateContactsShortcuts(db)) {
589 version = 6;
590 }
591 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000592
593 if (version < 7) {
594 // Version 7 gets rid of the special search widget.
595 convertWidgets(db);
596 version = 7;
597 }
598
Joe Onorato0589f0f2010-02-08 13:44:00 -0800599 if (version < 8) {
600 // Version 8 (froyo) has the icons all normalized. This should
601 // already be the case in practice, but we now rely on it and don't
602 // resample the images each time.
603 normalizeIcons(db);
604 version = 8;
605 }
606
Winson Chung3d503fb2011-07-13 17:25:49 -0700607 if (version < 9) {
608 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
609 // 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 -0700610 if (mMaxItemId == -1) {
611 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700612 }
613
614 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800615 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700616 version = 9;
617 }
618
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700619 // We bumped the version three time during JB, once to update the launch flags, once to
620 // update the override for the default launch animation and once to set the mimetype
621 // to improve startup performance
622 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700623 // Contact shortcuts need a different set of flags to be launched now
624 // The updateContactsShortcuts change is idempotent, so we can keep using it like
625 // back in the Donut days
626 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700627 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700628 }
629
Adam Cohendcd297f2013-06-18 13:13:40 -0700630 if (version < 13) {
631 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
632 // to persist workspace screens and their relative order.
633 mMaxScreenId = 0;
634
635 // This will never happen in the wild, but when we switch to using workspace
636 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700637 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700638
639 addWorkspacesTable(db);
640 version = 13;
641 }
642
Chris Wrend5e66bf2013-09-16 14:02:29 -0400643 if (version < 14) {
644 db.beginTransaction();
645 try {
646 // Insert new column for holding widget provider name
647 db.execSQL("ALTER TABLE favorites " +
648 "ADD COLUMN appWidgetProvider TEXT;");
649 db.setTransactionSuccessful();
650 version = 14;
651 } catch (SQLException ex) {
652 // Old version remains, which means we wipe old data
653 Log.e(TAG, ex.getMessage(), ex);
654 } finally {
655 db.endTransaction();
656 }
657 }
658
Chris Wren1ada10d2013-09-13 18:01:38 -0400659
660 if (version < 15) {
661 db.beginTransaction();
662 try {
663 // Insert new column for holding update timestamp
664 db.execSQL("ALTER TABLE favorites " +
665 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
666 db.execSQL("ALTER TABLE workspaceScreens " +
667 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
668 db.setTransactionSuccessful();
669 version = 15;
670 } catch (SQLException ex) {
671 // Old version remains, which means we wipe old data
672 Log.e(TAG, ex.getMessage(), ex);
673 } finally {
674 db.endTransaction();
675 }
676 }
677
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800679 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800680 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700681 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
682
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800683 onCreate(db);
684 }
685 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800686
687 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800688 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
689 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
690
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700691 Cursor c = null;
692 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800693 db.beginTransaction();
694 try {
695 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700696 c = db.query(TABLE_FAVORITES,
697 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800698 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700699 if (c == null) return false;
700
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800701 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700702
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800703 final int idIndex = c.getColumnIndex(Favorites._ID);
704 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700705
706 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800707 long favoriteId = c.getLong(idIndex);
708 final String intentUri = c.getString(intentIndex);
709 if (intentUri != null) {
710 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700711 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800712 android.util.Log.d("Home", intent.toString());
713 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700714 if (uri != null) {
715 final String data = uri.toString();
716 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
717 actionQuickContact.equals(intent.getAction())) &&
718 (data.startsWith("content://contacts/people/") ||
719 data.startsWith("content://com.android.contacts/" +
720 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800721
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700722 final Intent newIntent = new Intent(actionQuickContact);
723 // When starting from the launcher, start in a new, cleared task
724 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
725 // clear the whole thing preemptively here since
726 // QuickContactActivity will finish itself when launching other
727 // detail activities.
728 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
729 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700730 newIntent.putExtra(
731 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700732 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700733 // Determine the type and also put that in the shortcut
734 // (that can speed up launch a bit)
735 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800736
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700737 final ContentValues values = new ContentValues();
738 values.put(LauncherSettings.Favorites.INTENT,
739 newIntent.toUri(0));
740
741 String updateWhere = Favorites._ID + "=" + favoriteId;
742 db.update(TABLE_FAVORITES, values, updateWhere, null);
743 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800744 }
745 } catch (RuntimeException ex) {
746 Log.e(TAG, "Problem upgrading shortcut", ex);
747 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700748 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800749 }
750 }
751 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700752
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800753 db.setTransactionSuccessful();
754 } catch (SQLException ex) {
755 Log.w(TAG, "Problem while upgrading contacts", ex);
756 return false;
757 } finally {
758 db.endTransaction();
759 if (c != null) {
760 c.close();
761 }
762 }
763
764 return true;
765 }
766
Joe Onorato0589f0f2010-02-08 13:44:00 -0800767 private void normalizeIcons(SQLiteDatabase db) {
768 Log.d(TAG, "normalizing icons");
769
Joe Onorato346e1292010-02-18 10:34:24 -0500770 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800771 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400772 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800773 try {
774 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400775 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600776 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800777
778 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
779 Favorites.ICON_TYPE_BITMAP, null);
780
781 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
782 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
783
784 while (c.moveToNext()) {
785 long id = c.getLong(idIndex);
786 byte[] data = c.getBlob(iconIndex);
787 try {
788 Bitmap bitmap = Utilities.resampleIconBitmap(
789 BitmapFactory.decodeByteArray(data, 0, data.length),
790 mContext);
791 if (bitmap != null) {
792 update.bindLong(1, id);
793 data = ItemInfo.flattenBitmap(bitmap);
794 if (data != null) {
795 update.bindBlob(2, data);
796 update.execute();
797 }
798 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800799 }
800 } catch (Exception e) {
801 if (!logged) {
802 Log.e(TAG, "Failed normalizing icon " + id, e);
803 } else {
804 Log.e(TAG, "Also failed normalizing icon " + id);
805 }
806 logged = true;
807 }
808 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000809 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800810 } catch (SQLException ex) {
811 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
812 } finally {
813 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400814 if (update != null) {
815 update.close();
816 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800817 if (c != null) {
818 c.close();
819 }
820 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700821 }
822
823 // Generates a new ID to use for an object in your database. This method should be only
824 // called from the main UI thread. As an exception, we do call it when we call the
825 // constructor from the worker thread; however, this doesn't extend until after the
826 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
827 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 public long generateNewItemId() {
829 if (mMaxItemId < 0) {
830 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700831 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700832 mMaxItemId += 1;
833 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700834 }
835
Winson Chungc763c4e2013-07-19 13:49:06 -0700836 public void updateMaxItemId(long id) {
837 mMaxItemId = id + 1;
838 }
839
Adam Cohendcd297f2013-06-18 13:13:40 -0700840 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700841 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
842
843 // get the result
844 final int maxIdIndex = 0;
845 long id = -1;
846 if (c != null && c.moveToNext()) {
847 id = c.getLong(maxIdIndex);
848 }
Michael Jurka5130e402011-10-13 04:55:35 -0700849 if (c != null) {
850 c.close();
851 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700852
853 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 throw new RuntimeException("Error: could not query max item id");
855 }
856
857 return id;
858 }
859
860 // Generates a new ID to use for an workspace screen in your database. This method
861 // should be only called from the main UI thread. As an exception, we do call it when we
862 // call the constructor from the worker thread; however, this doesn't extend until after the
863 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
864 // after that point
865 public long generateNewScreenId() {
866 if (mMaxScreenId < 0) {
867 throw new RuntimeException("Error: max screen id was not initialized");
868 }
869 mMaxScreenId += 1;
870 return mMaxScreenId;
871 }
872
873 public void updateMaxScreenId(long maxScreenId) {
874 mMaxScreenId = maxScreenId;
875 }
876
877 private long initializeMaxScreenId(SQLiteDatabase db) {
878 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
879
880 // get the result
881 final int maxIdIndex = 0;
882 long id = -1;
883 if (c != null && c.moveToNext()) {
884 id = c.getLong(maxIdIndex);
885 }
886 if (c != null) {
887 c.close();
888 }
889
890 if (id == -1) {
891 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700892 }
893
894 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800895 }
896
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800897 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700898 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +0000899 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 */
901 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +0000902 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800903 final int[] bindSources = new int[] {
904 Favorites.ITEM_TYPE_WIDGET_CLOCK,
905 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +0000906 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800907 };
Bjorn Bringert7984c942009-12-09 15:38:25 +0000908
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800909 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700910
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800911 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700912
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800913 db.beginTransaction();
914 try {
915 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +0000916 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800917 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700918
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800919 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700920
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800921 final ContentValues values = new ContentValues();
922 while (c != null && c.moveToNext()) {
923 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +0000924 int favoriteType = c.getInt(1);
925
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700926 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800927 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700928 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700929
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800930 if (LOGD) {
931 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
932 + " for favoriteId=" + favoriteId);
933 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800934 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +0000935 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
936 values.put(Favorites.APPWIDGET_ID, appWidgetId);
937
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800938 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +0000939 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
940 values.put(LauncherSettings.Favorites.SPANX, 4);
941 values.put(LauncherSettings.Favorites.SPANY, 1);
942 } else {
943 values.put(LauncherSettings.Favorites.SPANX, 2);
944 values.put(LauncherSettings.Favorites.SPANY, 2);
945 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800946
947 String updateWhere = Favorites._ID + "=" + favoriteId;
948 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +0000949
Bjorn Bringert34251342009-12-15 13:33:11 +0000950 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700951 // TODO: check return value
952 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000953 new ComponentName("com.android.alarmclock",
954 "com.android.alarmclock.AnalogAppWidgetProvider"));
955 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700956 // TODO: check return value
957 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000958 new ComponentName("com.android.camera",
959 "com.android.camera.PhotoAppWidgetProvider"));
960 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700961 // TODO: check return value
962 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +0000963 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +0000964 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800965 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800966 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800967 }
968 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700969
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800970 db.setTransactionSuccessful();
971 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800972 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800973 } finally {
974 db.endTransaction();
975 if (c != null) {
976 c.close();
977 }
978 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700979
980 // Update max item id
981 mMaxItemId = initializeMaxItemId(db);
982 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800983 }
984
Michael Jurka8b805b12012-04-18 14:23:14 -0700985 private static final void beginDocument(XmlPullParser parser, String firstElementName)
986 throws XmlPullParserException, IOException {
987 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -0700988 while ((type = parser.next()) != XmlPullParser.START_TAG
989 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700990 ;
991 }
992
Michael Jurka9bc8eba2012-05-21 20:36:44 -0700993 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700994 throw new XmlPullParserException("No start tag found");
995 }
996
997 if (!parser.getName().equals(firstElementName)) {
998 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
999 ", expected " + firstElementName);
1000 }
1001 }
1002
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001003 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001004 * Loads the default set of favorite packages from an xml file.
1005 *
1006 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001007 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001008 */
Winson Chung6d092682011-11-16 18:43:26 -08001009 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001010 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1011 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1012 ContentValues values = new ContentValues();
1013
1014 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 int i = 0;
1016 try {
Winson Chung6d092682011-11-16 18:43:26 -08001017 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001018 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001019 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001020
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001021 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001022
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001023 int type;
1024 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1025 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1026
1027 if (type != XmlPullParser.START_TAG) {
1028 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001029 }
1030
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001031 boolean added = false;
1032 final String name = parser.getName();
1033
1034 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1035
Winson Chung3d503fb2011-07-13 17:25:49 -07001036 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1037 if (a.hasValue(R.styleable.Favorite_container)) {
1038 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1039 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001040
Winson Chung6d092682011-11-16 18:43:26 -08001041 String screen = a.getString(R.styleable.Favorite_screen);
1042 String x = a.getString(R.styleable.Favorite_x);
1043 String y = a.getString(R.styleable.Favorite_y);
1044
Winson Chung6d092682011-11-16 18:43:26 -08001045 values.clear();
1046 values.put(LauncherSettings.Favorites.CONTAINER, container);
1047 values.put(LauncherSettings.Favorites.SCREEN, screen);
1048 values.put(LauncherSettings.Favorites.CELLX, x);
1049 values.put(LauncherSettings.Favorites.CELLY, y);
1050
1051 if (TAG_FAVORITE.equals(name)) {
1052 long id = addAppShortcut(db, values, a, packageManager, intent);
1053 added = id >= 0;
1054 } else if (TAG_SEARCH.equals(name)) {
1055 added = addSearchWidget(db, values);
1056 } else if (TAG_CLOCK.equals(name)) {
1057 added = addClockWidget(db, values);
1058 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001059 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001060 } else if (TAG_SHORTCUT.equals(name)) {
1061 long id = addUriShortcut(db, values, a);
1062 added = id >= 0;
1063 } else if (TAG_FOLDER.equals(name)) {
1064 String title;
1065 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1066 if (titleResId != -1) {
1067 title = mContext.getResources().getString(titleResId);
1068 } else {
1069 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001070 }
Winson Chung6d092682011-11-16 18:43:26 -08001071 values.put(LauncherSettings.Favorites.TITLE, title);
1072 long folderId = addFolder(db, values);
1073 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001074
Winson Chung6d092682011-11-16 18:43:26 -08001075 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001076
Winson Chung6d092682011-11-16 18:43:26 -08001077 int folderDepth = parser.getDepth();
1078 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1079 parser.getDepth() > folderDepth) {
1080 if (type != XmlPullParser.START_TAG) {
1081 continue;
1082 }
1083 final String folder_item_name = parser.getName();
1084
1085 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1086 R.styleable.Favorite);
1087 values.clear();
1088 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1089
1090 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1091 long id =
1092 addAppShortcut(db, values, ar, packageManager, intent);
1093 if (id >= 0) {
1094 folderItems.add(id);
1095 }
1096 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1097 long id = addUriShortcut(db, values, ar);
1098 if (id >= 0) {
1099 folderItems.add(id);
1100 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001101 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001102 throw new RuntimeException("Folders can " +
1103 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001104 }
Winson Chung6d092682011-11-16 18:43:26 -08001105 ar.recycle();
1106 }
1107 // We can only have folders with >= 2 items, so we need to remove the
1108 // folder and clean up if less than 2 items were included, or some
1109 // failed to add, and less than 2 were actually added
1110 if (folderItems.size() < 2 && folderId >= 0) {
1111 // We just delete the folder and any items that made it
1112 deleteId(db, folderId);
1113 if (folderItems.size() > 0) {
1114 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001115 }
Winson Chung6d092682011-11-16 18:43:26 -08001116 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001117 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001118 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001119 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001120 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001121 }
1122 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001123 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001124 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001125 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001126 } catch (RuntimeException e) {
1127 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001128 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001129
Winson Chungc763c4e2013-07-19 13:49:06 -07001130 // Update the max item id after we have loaded the database
1131 if (mMaxItemId == -1) {
1132 mMaxItemId = initializeMaxItemId(db);
1133 }
1134
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001135 return i;
1136 }
1137
Adam Cohen228da5a2011-07-27 22:23:47 -07001138 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001139 PackageManager packageManager, Intent intent) {
Adam Cohen228da5a2011-07-27 22:23:47 -07001140 long id = -1;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001141 ActivityInfo info;
1142 String packageName = a.getString(R.styleable.Favorite_packageName);
1143 String className = a.getString(R.styleable.Favorite_className);
1144 try {
Romain Guy693599f2010-03-23 10:58:18 -07001145 ComponentName cn;
1146 try {
1147 cn = new ComponentName(packageName, className);
1148 info = packageManager.getActivityInfo(cn, 0);
1149 } catch (PackageManager.NameNotFoundException nnfe) {
1150 String[] packages = packageManager.currentToCanonicalPackageNames(
1151 new String[] { packageName });
1152 cn = new ComponentName(packages[0], className);
1153 info = packageManager.getActivityInfo(cn, 0);
1154 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 id = generateNewItemId();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001156 intent.setComponent(cn);
Romain Guy693599f2010-03-23 10:58:18 -07001157 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1158 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Romain Guy1ce1a242009-06-23 17:34:54 -07001159 values.put(Favorites.INTENT, intent.toUri(0));
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001160 values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
1161 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1162 values.put(Favorites.SPANX, 1);
1163 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001164 values.put(Favorites._ID, generateNewItemId());
Adam Cohen228da5a2011-07-27 22:23:47 -07001165 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1166 return -1;
1167 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001168 } catch (PackageManager.NameNotFoundException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001169 Log.w(TAG, "Unable to add favorite: " + packageName +
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001170 "/" + className, e);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001171 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001172 return id;
1173 }
1174
1175 private long addFolder(SQLiteDatabase db, ContentValues values) {
1176 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1177 values.put(Favorites.SPANX, 1);
1178 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001179 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001180 values.put(Favorites._ID, id);
1181 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1182 return -1;
1183 } else {
1184 return id;
1185 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001186 }
1187
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001188 private ComponentName getSearchWidgetProvider() {
1189 SearchManager searchManager =
1190 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1191 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1192 if (searchComponent == null) return null;
1193 return getProviderInPackage(searchComponent.getPackageName());
1194 }
1195
1196 /**
1197 * Gets an appwidget provider from the given package. If the package contains more than
1198 * one appwidget provider, an arbitrary one is returned.
1199 */
1200 private ComponentName getProviderInPackage(String packageName) {
1201 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1202 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1203 if (providers == null) return null;
1204 final int providerCount = providers.size();
1205 for (int i = 0; i < providerCount; i++) {
1206 ComponentName provider = providers.get(i).provider;
1207 if (provider != null && provider.getPackageName().equals(packageName)) {
1208 return provider;
1209 }
1210 }
1211 return null;
1212 }
1213
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001214 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001215 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001216 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001217 }
1218
1219 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001220 ComponentName cn = new ComponentName("com.android.alarmclock",
1221 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001222 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001223 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001224
Winson Chungb3302ae2012-05-01 10:19:14 -07001225 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1226 SQLiteDatabase db, ContentValues values, TypedArray a,
1227 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001228
Mike Cleronb87bd162009-10-30 16:36:56 -07001229 String packageName = a.getString(R.styleable.Favorite_packageName);
1230 String className = a.getString(R.styleable.Favorite_className);
1231
1232 if (packageName == null || className == null) {
1233 return false;
1234 }
Romain Guy693599f2010-03-23 10:58:18 -07001235
1236 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001237 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001238 try {
1239 packageManager.getReceiverInfo(cn, 0);
1240 } catch (Exception e) {
1241 String[] packages = packageManager.currentToCanonicalPackageNames(
1242 new String[] { packageName });
1243 cn = new ComponentName(packages[0], className);
1244 try {
1245 packageManager.getReceiverInfo(cn, 0);
1246 } catch (Exception e1) {
1247 hasPackage = false;
1248 }
1249 }
1250
1251 if (hasPackage) {
1252 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1253 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001254
1255 // Read the extras
1256 Bundle extras = new Bundle();
1257 int widgetDepth = parser.getDepth();
1258 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1259 parser.getDepth() > widgetDepth) {
1260 if (type != XmlPullParser.START_TAG) {
1261 continue;
1262 }
1263
1264 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1265 if (TAG_EXTRA.equals(parser.getName())) {
1266 String key = ar.getString(R.styleable.Extra_key);
1267 String value = ar.getString(R.styleable.Extra_value);
1268 if (key != null && value != null) {
1269 extras.putString(key, value);
1270 } else {
1271 throw new RuntimeException("Widget extras must have a key and value");
1272 }
1273 } else {
1274 throw new RuntimeException("Widgets can contain only extras");
1275 }
1276 ar.recycle();
1277 }
1278
1279 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001280 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001281
Romain Guy693599f2010-03-23 10:58:18 -07001282 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001283 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001284 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001285 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001286 boolean allocatedAppWidgets = false;
1287 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1288
1289 try {
1290 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001291
Mike Cleronb87bd162009-10-30 16:36:56 -07001292 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001293 values.put(Favorites.SPANX, spanX);
1294 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001295 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001296 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001297 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001298 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001299
1300 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001301
Michael Jurka8b805b12012-04-18 14:23:14 -07001302 // TODO: need to check return value
1303 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001304
1305 // Send a broadcast to configure the widget
1306 if (extras != null && !extras.isEmpty()) {
1307 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1308 intent.setComponent(cn);
1309 intent.putExtras(extras);
1310 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1311 mContext.sendBroadcast(intent);
1312 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001313 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001314 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001315 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001316
Mike Cleronb87bd162009-10-30 16:36:56 -07001317 return allocatedAppWidgets;
1318 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001319
1320 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001321 TypedArray a) {
1322 Resources r = mContext.getResources();
1323
1324 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1325 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1326
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001327 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001328 String uri = null;
1329 try {
1330 uri = a.getString(R.styleable.Favorite_uri);
1331 intent = Intent.parseUri(uri, 0);
1332 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001333 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001334 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001335 }
1336
1337 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001338 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001339 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001340 }
1341
Adam Cohendcd297f2013-06-18 13:13:40 -07001342 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001343 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1344 values.put(Favorites.INTENT, intent.toUri(0));
1345 values.put(Favorites.TITLE, r.getString(titleResId));
1346 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1347 values.put(Favorites.SPANX, 1);
1348 values.put(Favorites.SPANY, 1);
1349 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1350 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1351 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001352 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001353
Adam Cohen228da5a2011-07-27 22:23:47 -07001354 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1355 return -1;
1356 }
1357 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001358 }
1359 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001360
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001361 /**
1362 * Build a query string that will match any row where the column matches
1363 * anything in the values list.
1364 */
1365 static String buildOrWhereString(String column, int[] values) {
1366 StringBuilder selectWhere = new StringBuilder();
1367 for (int i = values.length - 1; i >= 0; i--) {
1368 selectWhere.append(column).append("=").append(values[i]);
1369 if (i > 0) {
1370 selectWhere.append(" OR ");
1371 }
1372 }
1373 return selectWhere.toString();
1374 }
1375
1376 static class SqlArguments {
1377 public final String table;
1378 public final String where;
1379 public final String[] args;
1380
1381 SqlArguments(Uri url, String where, String[] args) {
1382 if (url.getPathSegments().size() == 1) {
1383 this.table = url.getPathSegments().get(0);
1384 this.where = where;
1385 this.args = args;
1386 } else if (url.getPathSegments().size() != 2) {
1387 throw new IllegalArgumentException("Invalid URI: " + url);
1388 } else if (!TextUtils.isEmpty(where)) {
1389 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1390 } else {
1391 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001392 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001393 this.args = null;
1394 }
1395 }
1396
1397 SqlArguments(Uri url) {
1398 if (url.getPathSegments().size() == 1) {
1399 table = url.getPathSegments().get(0);
1400 where = null;
1401 args = null;
1402 } else {
1403 throw new IllegalArgumentException("Invalid URI: " + url);
1404 }
1405 }
1406 }
1407}