blob: b5db3386f843ff956686478a9947fa7ac1e7f472 [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
Daniel Sandler325dc232013-06-05 22:57:57 -040052import com.android.launcher3.LauncherSettings.Favorites;
Chris Wrene523e702013-10-09 10:36:55 -040053import com.android.launcher3.config.ProviderConfig;
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";
Chris Wrene523e702013-10-09 10:36:55 -040072 static final String AUTHORITY = ProviderConfig.AUTHORITY;
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;
Winson Chunga90303b2013-11-15 13:05:06 -0800871 // Log to disk
872 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700873 return mMaxScreenId;
874 }
875
876 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800877 // Log to disk
878 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700879 mMaxScreenId = maxScreenId;
880 }
881
882 private long initializeMaxScreenId(SQLiteDatabase db) {
883 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
884
885 // get the result
886 final int maxIdIndex = 0;
887 long id = -1;
888 if (c != null && c.moveToNext()) {
889 id = c.getLong(maxIdIndex);
890 }
891 if (c != null) {
892 c.close();
893 }
894
895 if (id == -1) {
896 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700897 }
898
Winson Chunga90303b2013-11-15 13:05:06 -0800899 // Log to disk
900 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700901 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800902 }
903
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800904 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700905 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +0000906 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800907 */
908 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +0000909 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800910 final int[] bindSources = new int[] {
911 Favorites.ITEM_TYPE_WIDGET_CLOCK,
912 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +0000913 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800914 };
Bjorn Bringert7984c942009-12-09 15:38:25 +0000915
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800916 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700917
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800918 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700919
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800920 db.beginTransaction();
921 try {
922 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +0000923 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800924 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700925
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800926 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700927
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928 final ContentValues values = new ContentValues();
929 while (c != null && c.moveToNext()) {
930 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +0000931 int favoriteType = c.getInt(1);
932
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700933 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800934 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700935 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700936
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800937 if (LOGD) {
938 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
939 + " for favoriteId=" + favoriteId);
940 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800941 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +0000942 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
943 values.put(Favorites.APPWIDGET_ID, appWidgetId);
944
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +0000946 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
947 values.put(LauncherSettings.Favorites.SPANX, 4);
948 values.put(LauncherSettings.Favorites.SPANY, 1);
949 } else {
950 values.put(LauncherSettings.Favorites.SPANX, 2);
951 values.put(LauncherSettings.Favorites.SPANY, 2);
952 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800953
954 String updateWhere = Favorites._ID + "=" + favoriteId;
955 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +0000956
Bjorn Bringert34251342009-12-15 13:33:11 +0000957 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700958 // TODO: check return value
959 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000960 new ComponentName("com.android.alarmclock",
961 "com.android.alarmclock.AnalogAppWidgetProvider"));
962 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700963 // TODO: check return value
964 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000965 new ComponentName("com.android.camera",
966 "com.android.camera.PhotoAppWidgetProvider"));
967 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700968 // TODO: check return value
969 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +0000970 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +0000971 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800972 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800973 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800974 }
975 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700976
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800977 db.setTransactionSuccessful();
978 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800979 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800980 } finally {
981 db.endTransaction();
982 if (c != null) {
983 c.close();
984 }
985 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700986
987 // Update max item id
988 mMaxItemId = initializeMaxItemId(db);
989 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800990 }
991
Michael Jurka8b805b12012-04-18 14:23:14 -0700992 private static final void beginDocument(XmlPullParser parser, String firstElementName)
993 throws XmlPullParserException, IOException {
994 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -0700995 while ((type = parser.next()) != XmlPullParser.START_TAG
996 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700997 ;
998 }
999
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001000 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001001 throw new XmlPullParserException("No start tag found");
1002 }
1003
1004 if (!parser.getName().equals(firstElementName)) {
1005 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1006 ", expected " + firstElementName);
1007 }
1008 }
1009
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001010 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001011 * Loads the default set of favorite packages from an xml file.
1012 *
1013 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001014 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 */
Winson Chung6d092682011-11-16 18:43:26 -08001016 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001017 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1018 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1019 ContentValues values = new ContentValues();
1020
Daniel Sandler57dac262013-10-03 13:28:36 -04001021 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1022
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001023 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001024 int i = 0;
1025 try {
Winson Chung6d092682011-11-16 18:43:26 -08001026 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001027 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001028 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001029
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001030 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001031
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001032 int type;
1033 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1034 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1035
1036 if (type != XmlPullParser.START_TAG) {
1037 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001038 }
1039
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001040 boolean added = false;
1041 final String name = parser.getName();
1042
Daniel Sandler57dac262013-10-03 13:28:36 -04001043 if (TAG_INCLUDE.equals(name)) {
1044 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1045
1046 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1047
1048 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1049 "", resId));
1050
1051 if (resId != 0 && resId != workspaceResourceId) {
1052 // recursively load some more favorites, why not?
1053 i += loadFavorites(db, resId);
1054 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001055 } else {
1056 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1057 }
1058
1059 a.recycle();
1060
1061 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1062 continue;
1063 }
1064
1065 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001066 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1067
Winson Chung3d503fb2011-07-13 17:25:49 -07001068 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1069 if (a.hasValue(R.styleable.Favorite_container)) {
1070 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1071 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001072
Winson Chung6d092682011-11-16 18:43:26 -08001073 String screen = a.getString(R.styleable.Favorite_screen);
1074 String x = a.getString(R.styleable.Favorite_x);
1075 String y = a.getString(R.styleable.Favorite_y);
1076
Winson Chung6d092682011-11-16 18:43:26 -08001077 values.clear();
1078 values.put(LauncherSettings.Favorites.CONTAINER, container);
1079 values.put(LauncherSettings.Favorites.SCREEN, screen);
1080 values.put(LauncherSettings.Favorites.CELLX, x);
1081 values.put(LauncherSettings.Favorites.CELLY, y);
1082
Daniel Sandler57dac262013-10-03 13:28:36 -04001083 if (LOGD) {
1084 final String title = a.getString(R.styleable.Favorite_title);
1085 final String pkg = a.getString(R.styleable.Favorite_packageName);
1086 final String something = title != null ? title : pkg;
1087 Log.v(TAG, String.format(
1088 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1089 "", name,
1090 (something == null ? "" : (" \"" + something + "\"")),
1091 container, screen, x, y));
1092 }
1093
Winson Chung6d092682011-11-16 18:43:26 -08001094 if (TAG_FAVORITE.equals(name)) {
1095 long id = addAppShortcut(db, values, a, packageManager, intent);
1096 added = id >= 0;
1097 } else if (TAG_SEARCH.equals(name)) {
1098 added = addSearchWidget(db, values);
1099 } else if (TAG_CLOCK.equals(name)) {
1100 added = addClockWidget(db, values);
1101 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001102 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001103 } else if (TAG_SHORTCUT.equals(name)) {
1104 long id = addUriShortcut(db, values, a);
1105 added = id >= 0;
1106 } else if (TAG_FOLDER.equals(name)) {
1107 String title;
1108 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1109 if (titleResId != -1) {
1110 title = mContext.getResources().getString(titleResId);
1111 } else {
1112 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001113 }
Winson Chung6d092682011-11-16 18:43:26 -08001114 values.put(LauncherSettings.Favorites.TITLE, title);
1115 long folderId = addFolder(db, values);
1116 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001117
Winson Chung6d092682011-11-16 18:43:26 -08001118 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001119
Winson Chung6d092682011-11-16 18:43:26 -08001120 int folderDepth = parser.getDepth();
1121 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1122 parser.getDepth() > folderDepth) {
1123 if (type != XmlPullParser.START_TAG) {
1124 continue;
1125 }
1126 final String folder_item_name = parser.getName();
1127
1128 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1129 R.styleable.Favorite);
1130 values.clear();
1131 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1132
Daniel Sandler57dac262013-10-03 13:28:36 -04001133 if (LOGD) {
1134 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1135 final String uri = ar.getString(R.styleable.Favorite_uri);
1136 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1137 folder_item_name, uri != null ? uri : pkg));
1138 }
1139
Winson Chung6d092682011-11-16 18:43:26 -08001140 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1141 long id =
1142 addAppShortcut(db, values, ar, packageManager, intent);
1143 if (id >= 0) {
1144 folderItems.add(id);
1145 }
1146 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1147 long id = addUriShortcut(db, values, ar);
1148 if (id >= 0) {
1149 folderItems.add(id);
1150 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001151 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001152 throw new RuntimeException("Folders can " +
1153 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001154 }
Winson Chung6d092682011-11-16 18:43:26 -08001155 ar.recycle();
1156 }
1157 // We can only have folders with >= 2 items, so we need to remove the
1158 // folder and clean up if less than 2 items were included, or some
1159 // failed to add, and less than 2 were actually added
1160 if (folderItems.size() < 2 && folderId >= 0) {
1161 // We just delete the folder and any items that made it
1162 deleteId(db, folderId);
1163 if (folderItems.size() > 0) {
1164 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001165 }
Winson Chung6d092682011-11-16 18:43:26 -08001166 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001167 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001168 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001169 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001170 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171 }
1172 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001173 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001174 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001175 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001176 } catch (RuntimeException e) {
1177 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001178 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001179
Winson Chungc763c4e2013-07-19 13:49:06 -07001180 // Update the max item id after we have loaded the database
1181 if (mMaxItemId == -1) {
1182 mMaxItemId = initializeMaxItemId(db);
1183 }
1184
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001185 return i;
1186 }
1187
Adam Cohen228da5a2011-07-27 22:23:47 -07001188 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001189 PackageManager packageManager, Intent intent) {
Adam Cohen228da5a2011-07-27 22:23:47 -07001190 long id = -1;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001191 ActivityInfo info;
1192 String packageName = a.getString(R.styleable.Favorite_packageName);
1193 String className = a.getString(R.styleable.Favorite_className);
1194 try {
Romain Guy693599f2010-03-23 10:58:18 -07001195 ComponentName cn;
1196 try {
1197 cn = new ComponentName(packageName, className);
1198 info = packageManager.getActivityInfo(cn, 0);
1199 } catch (PackageManager.NameNotFoundException nnfe) {
1200 String[] packages = packageManager.currentToCanonicalPackageNames(
1201 new String[] { packageName });
1202 cn = new ComponentName(packages[0], className);
1203 info = packageManager.getActivityInfo(cn, 0);
1204 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001205 id = generateNewItemId();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001206 intent.setComponent(cn);
Romain Guy693599f2010-03-23 10:58:18 -07001207 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1208 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Romain Guy1ce1a242009-06-23 17:34:54 -07001209 values.put(Favorites.INTENT, intent.toUri(0));
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001210 values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
1211 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1212 values.put(Favorites.SPANX, 1);
1213 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001214 values.put(Favorites._ID, generateNewItemId());
Adam Cohen228da5a2011-07-27 22:23:47 -07001215 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1216 return -1;
1217 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001218 } catch (PackageManager.NameNotFoundException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001219 Log.w(TAG, "Unable to add favorite: " + packageName +
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001220 "/" + className, e);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001221 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001222 return id;
1223 }
1224
1225 private long addFolder(SQLiteDatabase db, ContentValues values) {
1226 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1227 values.put(Favorites.SPANX, 1);
1228 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001229 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001230 values.put(Favorites._ID, id);
1231 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1232 return -1;
1233 } else {
1234 return id;
1235 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001236 }
1237
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001238 private ComponentName getSearchWidgetProvider() {
1239 SearchManager searchManager =
1240 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1241 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1242 if (searchComponent == null) return null;
1243 return getProviderInPackage(searchComponent.getPackageName());
1244 }
1245
1246 /**
1247 * Gets an appwidget provider from the given package. If the package contains more than
1248 * one appwidget provider, an arbitrary one is returned.
1249 */
1250 private ComponentName getProviderInPackage(String packageName) {
1251 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1252 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1253 if (providers == null) return null;
1254 final int providerCount = providers.size();
1255 for (int i = 0; i < providerCount; i++) {
1256 ComponentName provider = providers.get(i).provider;
1257 if (provider != null && provider.getPackageName().equals(packageName)) {
1258 return provider;
1259 }
1260 }
1261 return null;
1262 }
1263
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001264 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001265 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001266 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001267 }
1268
1269 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001270 ComponentName cn = new ComponentName("com.android.alarmclock",
1271 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001272 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001273 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001274
Winson Chungb3302ae2012-05-01 10:19:14 -07001275 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1276 SQLiteDatabase db, ContentValues values, TypedArray a,
1277 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001278
Mike Cleronb87bd162009-10-30 16:36:56 -07001279 String packageName = a.getString(R.styleable.Favorite_packageName);
1280 String className = a.getString(R.styleable.Favorite_className);
1281
1282 if (packageName == null || className == null) {
1283 return false;
1284 }
Romain Guy693599f2010-03-23 10:58:18 -07001285
1286 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001287 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001288 try {
1289 packageManager.getReceiverInfo(cn, 0);
1290 } catch (Exception e) {
1291 String[] packages = packageManager.currentToCanonicalPackageNames(
1292 new String[] { packageName });
1293 cn = new ComponentName(packages[0], className);
1294 try {
1295 packageManager.getReceiverInfo(cn, 0);
1296 } catch (Exception e1) {
1297 hasPackage = false;
1298 }
1299 }
1300
1301 if (hasPackage) {
1302 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1303 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001304
1305 // Read the extras
1306 Bundle extras = new Bundle();
1307 int widgetDepth = parser.getDepth();
1308 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1309 parser.getDepth() > widgetDepth) {
1310 if (type != XmlPullParser.START_TAG) {
1311 continue;
1312 }
1313
1314 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1315 if (TAG_EXTRA.equals(parser.getName())) {
1316 String key = ar.getString(R.styleable.Extra_key);
1317 String value = ar.getString(R.styleable.Extra_value);
1318 if (key != null && value != null) {
1319 extras.putString(key, value);
1320 } else {
1321 throw new RuntimeException("Widget extras must have a key and value");
1322 }
1323 } else {
1324 throw new RuntimeException("Widgets can contain only extras");
1325 }
1326 ar.recycle();
1327 }
1328
1329 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001330 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001331
Romain Guy693599f2010-03-23 10:58:18 -07001332 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001333 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001334 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001335 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001336 boolean allocatedAppWidgets = false;
1337 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1338
1339 try {
1340 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001341
Mike Cleronb87bd162009-10-30 16:36:56 -07001342 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001343 values.put(Favorites.SPANX, spanX);
1344 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001345 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001346 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001347 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001348 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001349
1350 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001351
Michael Jurka8b805b12012-04-18 14:23:14 -07001352 // TODO: need to check return value
1353 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001354
1355 // Send a broadcast to configure the widget
1356 if (extras != null && !extras.isEmpty()) {
1357 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1358 intent.setComponent(cn);
1359 intent.putExtras(extras);
1360 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1361 mContext.sendBroadcast(intent);
1362 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001363 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001364 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001365 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001366
Mike Cleronb87bd162009-10-30 16:36:56 -07001367 return allocatedAppWidgets;
1368 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001369
1370 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001371 TypedArray a) {
1372 Resources r = mContext.getResources();
1373
1374 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1375 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1376
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001377 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001378 String uri = null;
1379 try {
1380 uri = a.getString(R.styleable.Favorite_uri);
1381 intent = Intent.parseUri(uri, 0);
1382 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001383 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001384 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001385 }
1386
1387 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001388 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001389 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001390 }
1391
Adam Cohendcd297f2013-06-18 13:13:40 -07001392 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001393 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1394 values.put(Favorites.INTENT, intent.toUri(0));
1395 values.put(Favorites.TITLE, r.getString(titleResId));
1396 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1397 values.put(Favorites.SPANX, 1);
1398 values.put(Favorites.SPANY, 1);
1399 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1400 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1401 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001402 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001403
Adam Cohen228da5a2011-07-27 22:23:47 -07001404 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1405 return -1;
1406 }
1407 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001408 }
1409 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001410
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001411 /**
1412 * Build a query string that will match any row where the column matches
1413 * anything in the values list.
1414 */
1415 static String buildOrWhereString(String column, int[] values) {
1416 StringBuilder selectWhere = new StringBuilder();
1417 for (int i = values.length - 1; i >= 0; i--) {
1418 selectWhere.append(column).append("=").append(values[i]);
1419 if (i > 0) {
1420 selectWhere.append(" OR ");
1421 }
1422 }
1423 return selectWhere.toString();
1424 }
1425
1426 static class SqlArguments {
1427 public final String table;
1428 public final String where;
1429 public final String[] args;
1430
1431 SqlArguments(Uri url, String where, String[] args) {
1432 if (url.getPathSegments().size() == 1) {
1433 this.table = url.getPathSegments().get(0);
1434 this.where = where;
1435 this.args = args;
1436 } else if (url.getPathSegments().size() != 2) {
1437 throw new IllegalArgumentException("Invalid URI: " + url);
1438 } else if (!TextUtils.isEmpty(where)) {
1439 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1440 } else {
1441 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001442 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001443 this.args = null;
1444 }
1445 }
1446
1447 SqlArguments(Uri url) {
1448 if (url.getPathSegments().size() == 1) {
1449 table = url.getPathSegments().get(0);
1450 where = null;
1451 args = null;
1452 } else {
1453 throw new IllegalArgumentException("Invalid URI: " + url);
1454 }
1455 }
1456 }
1457}