blob: 28efd0148730bcb6cb3a1b9344ba2ad6783dcae0 [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
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050074 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd0e41182013-12-02 15:55:50 -050075 static final boolean IMPORT_LAUNCHER2_DATABASE = true;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050076
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070078 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070080 static final String UPGRADED_FROM_OLD_DATABASE =
81 "UPGRADED_FROM_OLD_DATABASE";
82 static final String EMPTY_DATABASE_CREATED =
83 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020084 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
85 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
Winson Chungb3302ae2012-05-01 10:19:14 -070087 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070088 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070089
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070090 /**
Romain Guy73b979d2009-06-09 12:57:21 -070091 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070092 * {@link AppWidgetHost#deleteHost()} is called during database creation.
93 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
94 */
95 static final Uri CONTENT_APPWIDGET_RESET_URI =
96 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070097
Michael Jurkaa8c760d2011-04-28 14:59:33 -070098 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -070099 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
101 @Override
102 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400103 final Context context = getContext();
104 mOpenHelper = new DatabaseHelper(context);
105 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106 return true;
107 }
108
109 @Override
110 public String getType(Uri uri) {
111 SqlArguments args = new SqlArguments(uri, null, null);
112 if (TextUtils.isEmpty(args.where)) {
113 return "vnd.android.cursor.dir/" + args.table;
114 } else {
115 return "vnd.android.cursor.item/" + args.table;
116 }
117 }
118
119 @Override
120 public Cursor query(Uri uri, String[] projection, String selection,
121 String[] selectionArgs, String sortOrder) {
122
123 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
124 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
125 qb.setTables(args.table);
126
Romain Guy73b979d2009-06-09 12:57:21 -0700127 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
129 result.setNotificationUri(getContext().getContentResolver(), uri);
130
131 return result;
132 }
133
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 private static long dbInsertAndCheck(DatabaseHelper helper,
135 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
136 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
137 throw new RuntimeException("Error: attempting to add item without specifying an id");
138 }
139 return db.insert(table, nullColumnHack, values);
140 }
141
Adam Cohen228da5a2011-07-27 22:23:47 -0700142 private static void deleteId(SQLiteDatabase db, long id) {
143 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
144 SqlArguments args = new SqlArguments(uri, null, null);
145 db.delete(args.table, args.where, args.args);
146 }
147
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800148 @Override
149 public Uri insert(Uri uri, ContentValues initialValues) {
150 SqlArguments args = new SqlArguments(uri);
151
152 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400153 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 if (rowId <= 0) return null;
156
157 uri = ContentUris.withAppendedId(uri, rowId);
158 sendNotify(uri);
159
160 return uri;
161 }
162
163 @Override
164 public int bulkInsert(Uri uri, ContentValues[] values) {
165 SqlArguments args = new SqlArguments(uri);
166
167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
168 db.beginTransaction();
169 try {
170 int numValues = values.length;
171 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400172 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
174 return 0;
175 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176 }
177 db.setTransactionSuccessful();
178 } finally {
179 db.endTransaction();
180 }
181
182 sendNotify(uri);
183 return values.length;
184 }
185
186 @Override
187 public int delete(Uri uri, String selection, String[] selectionArgs) {
188 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
189
190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
191 int count = db.delete(args.table, args.where, args.args);
192 if (count > 0) sendNotify(uri);
193
194 return count;
195 }
196
197 @Override
198 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
199 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
200
Chris Wren1ada10d2013-09-13 18:01:38 -0400201 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
203 int count = db.update(args.table, values, args.where, args.args);
204 if (count > 0) sendNotify(uri);
205
206 return count;
207 }
208
209 private void sendNotify(Uri uri) {
210 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
211 if (notify == null || "true".equals(notify)) {
212 getContext().getContentResolver().notifyChange(uri, null);
213 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400214
215 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400216 LauncherBackupAgentHelper.dataChanged(getContext());
Chris Wren1ada10d2013-09-13 18:01:38 -0400217 }
218
219 private void addModifiedTime(ContentValues values) {
220 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 }
222
Adam Cohendcd297f2013-06-18 13:13:40 -0700223 public long generateNewItemId() {
224 return mOpenHelper.generateNewItemId();
225 }
226
Winson Chungc763c4e2013-07-19 13:49:06 -0700227 public void updateMaxItemId(long id) {
228 mOpenHelper.updateMaxItemId(id);
229 }
230
Adam Cohendcd297f2013-06-18 13:13:40 -0700231 public long generateNewScreenId() {
232 return mOpenHelper.generateNewScreenId();
233 }
234
235 // This is only required one time while loading the workspace during the
236 // upgrade path, and should never be called from anywhere else.
237 public void updateMaxScreenId(long maxScreenId) {
238 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700239 }
240
Brian Muramatsu5524b492012-10-02 16:55:54 -0700241 /**
Adam Cohene25af792013-06-06 23:08:25 -0700242 * @param Should we load the old db for upgrade? first run only.
243 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700244 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400245 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700246 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
247
Winson Chungc763c4e2013-07-19 13:49:06 -0700248 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700249
Winson Chungc763c4e2013-07-19 13:49:06 -0700250 sJustLoadedFromOldDb = false;
251 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700252
253 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700254 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700255 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700256 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700257 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700258 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700259 }
260
261 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700262 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
263 */
Michael Jurka45355c42012-10-08 13:21:35 +0200264 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400265 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700266 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700267
Winson Chungc763c4e2013-07-19 13:49:06 -0700268 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Michael Jurka45355c42012-10-08 13:21:35 +0200269 int workspaceResId = origWorkspaceResId;
270
Brian Muramatsu5524b492012-10-02 16:55:54 -0700271 // Use default workspace resource if none provided
272 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800273 workspaceResId =
274 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700275 }
276
Michael Jurkab85f8a42012-04-25 15:48:32 -0700277 // Populate favorites table with initial favorites
278 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700279 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200280 if (origWorkspaceResId != 0) {
281 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
282 }
Adam Cohene25af792013-06-06 23:08:25 -0700283
Brian Muramatsu5524b492012-10-02 16:55:54 -0700284 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700285 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700286 editor.commit();
287 }
288 }
289
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800290 private static int getDefaultWorkspaceResourceId() {
291 if (AppsCustomizePagedView.DISABLE_ALL_APPS) {
292 return R.xml.default_workspace_no_all_apps;
293 } else {
294 return R.xml.default_workspace;
295 }
296 }
297
Winson Chungc763c4e2013-07-19 13:49:06 -0700298 private static interface ContentValuesCallback {
299 public void onRow(ContentValues values);
300 }
301
Adam Cohen6dbe0492013-12-02 17:00:14 -0800302 private static boolean shouldImportLauncher2Database(Context context) {
303 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
304
305 // We don't import the old databse for tablets, as the grid size has changed.
306 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
307 }
308
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800309 private static class DatabaseHelper extends SQLiteOpenHelper {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800310 private static final String TAG_FAVORITES = "favorites";
311 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700312 private static final String TAG_CLOCK = "clock";
313 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700314 private static final String TAG_APPWIDGET = "appwidget";
315 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700316 private static final String TAG_FOLDER = "folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700317 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400318 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700319
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800320 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700321 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700322 private long mMaxItemId = -1;
323 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324
325 DatabaseHelper(Context context) {
326 super(context, DATABASE_NAME, null, DATABASE_VERSION);
327 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700328 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700329
330 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
331 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700332 if (mMaxItemId == -1) {
333 mMaxItemId = initializeMaxItemId(getWritableDatabase());
334 }
335 if (mMaxScreenId == -1) {
336 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700337 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338 }
339
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700340 /**
341 * Send notification that we've deleted the {@link AppWidgetHost},
342 * probably as part of the initial database creation. The receiver may
343 * want to re-call {@link AppWidgetHost#startListening()} to ensure
344 * callbacks are correctly set.
345 */
346 private void sendAppWidgetResetNotify() {
347 final ContentResolver resolver = mContext.getContentResolver();
348 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
349 }
350
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 @Override
352 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800353 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700354
Adam Cohendcd297f2013-06-18 13:13:40 -0700355 mMaxItemId = 1;
356 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700357
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800358 db.execSQL("CREATE TABLE favorites (" +
359 "_id INTEGER PRIMARY KEY," +
360 "title TEXT," +
361 "intent TEXT," +
362 "container INTEGER," +
363 "screen INTEGER," +
364 "cellX INTEGER," +
365 "cellY INTEGER," +
366 "spanX INTEGER," +
367 "spanY INTEGER," +
368 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700369 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800370 "isShortcut INTEGER," +
371 "iconType INTEGER," +
372 "iconPackage TEXT," +
373 "iconResource TEXT," +
374 "icon BLOB," +
375 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400376 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400377 "appWidgetProvider TEXT," +
378 "modified INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800379 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700380 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800381
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700382 // Database was just created, so wipe any previous widgets
383 if (mAppWidgetHost != null) {
384 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700385 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800386 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700387
Adam Cohen6dbe0492013-12-02 17:00:14 -0800388 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500389 // Try converting the old database
390 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
391 public void onRow(ContentValues values) {
392 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
393 if (container == Favorites.CONTAINER_DESKTOP) {
394 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
395 screen = (int) upgradeLauncherDb_permuteScreens(screen);
396 values.put(LauncherSettings.Favorites.SCREEN, screen);
397 }
398 }
399 };
400 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
401 "/old_favorites?notify=true");
402 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
403 // Try and upgrade from the Launcher2 db
404 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
405 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
406 // If we fail, then set a flag to load the default workspace
407 setFlagEmptyDbCreated();
408 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700409 }
410 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500411 // Right now, in non-default workspace cases, we want to run the final
412 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
413 // set that flag too.
414 setFlagJustLoadedOldDb();
415 } else {
416 // Fresh and clean launcher DB.
417 mMaxItemId = initializeMaxItemId(db);
418 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800419 }
420 }
421
Adam Cohendcd297f2013-06-18 13:13:40 -0700422 private void addWorkspacesTable(SQLiteDatabase db) {
423 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
424 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
426 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700427 ");");
428 }
429
Winson Chungc763c4e2013-07-19 13:49:06 -0700430 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400431 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700432 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
433 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700434 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
435 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700436 editor.commit();
437 }
438
Winson Chungc763c4e2013-07-19 13:49:06 -0700439 private void setFlagEmptyDbCreated() {
440 String spKey = LauncherAppState.getSharedPreferencesKey();
441 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
442 SharedPreferences.Editor editor = sp.edit();
443 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
444 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
445 editor.commit();
446 }
447
448 // We rearrange the screens from the old launcher
449 // 12345 -> 34512
450 private long upgradeLauncherDb_permuteScreens(long screen) {
451 if (screen >= 2) {
452 return screen - 2;
453 } else {
454 return screen + 3;
455 }
456 }
457
458 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
459 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800460 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800461 boolean converted = false;
462
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463 final ContentResolver resolver = mContext.getContentResolver();
464 Cursor cursor = null;
465
466 try {
467 cursor = resolver.query(uri, null, null, null, null);
468 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700469 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800470 }
471
472 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700473 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700475 if (cursor.getCount() > 0) {
476 converted = copyFromCursor(db, cursor, cb) > 0;
477 if (converted && deleteRows) {
478 resolver.delete(uri, null, null);
479 }
480 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800481 } finally {
482 cursor.close();
483 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700485
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800486 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700487 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800488 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800489 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700490
491 // Update max item id
492 mMaxItemId = initializeMaxItemId(db);
493 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494 }
495
496 return converted;
497 }
498
Winson Chungc763c4e2013-07-19 13:49:06 -0700499 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700500 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800501 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
502 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
503 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
504 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
505 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
506 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
507 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
508 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
509 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
510 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
511 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
512 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
513 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
514
515 ContentValues[] rows = new ContentValues[c.getCount()];
516 int i = 0;
517 while (c.moveToNext()) {
518 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700519 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800520 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
521 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
522 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
523 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
524 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
525 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
526 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
527 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700528 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800529 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
530 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
531 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
532 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
533 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700534 if (cb != null) {
535 cb.onRow(values);
536 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800537 rows[i++] = values;
538 }
539
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700541 if (i > 0) {
542 db.beginTransaction();
543 try {
544 int numValues = rows.length;
545 for (i = 0; i < numValues; i++) {
546 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
547 return 0;
548 } else {
549 total++;
550 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700552 db.setTransactionSuccessful();
553 } finally {
554 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800555 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800556 }
557
558 return total;
559 }
560
561 @Override
562 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700563 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700564
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700566 if (version < 3) {
567 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800568 db.beginTransaction();
569 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700570 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800571 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700572 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700574 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 } catch (SQLException ex) {
576 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800577 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 } finally {
579 db.endTransaction();
580 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700581
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700583 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 convertWidgets(db);
585 }
586 }
Romain Guy73b979d2009-06-09 12:57:21 -0700587
588 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800589 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700590 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700591
Romain Guy509cd6a2010-03-23 15:10:56 -0700592 // Where's version 5?
593 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400594 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700595 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
596 // but version 5 on there was the updateContactsShortcuts change
597 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
598 // The updateContactsShortcuts change is idempotent, so running it twice
599 // is okay so we'll do that when upgrading the devices that shipped with it.
600 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800601 // We went from 3 to 5 screens. Move everything 1 to the right
602 db.beginTransaction();
603 try {
604 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
605 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800606 } catch (SQLException ex) {
607 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800608 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800609 } finally {
610 db.endTransaction();
611 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700612
Romain Guy509cd6a2010-03-23 15:10:56 -0700613 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800614 if (updateContactsShortcuts(db)) {
615 version = 6;
616 }
617 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000618
619 if (version < 7) {
620 // Version 7 gets rid of the special search widget.
621 convertWidgets(db);
622 version = 7;
623 }
624
Joe Onorato0589f0f2010-02-08 13:44:00 -0800625 if (version < 8) {
626 // Version 8 (froyo) has the icons all normalized. This should
627 // already be the case in practice, but we now rely on it and don't
628 // resample the images each time.
629 normalizeIcons(db);
630 version = 8;
631 }
632
Winson Chung3d503fb2011-07-13 17:25:49 -0700633 if (version < 9) {
634 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
635 // 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 -0700636 if (mMaxItemId == -1) {
637 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700638 }
639
640 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800641 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700642 version = 9;
643 }
644
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700645 // We bumped the version three time during JB, once to update the launch flags, once to
646 // update the override for the default launch animation and once to set the mimetype
647 // to improve startup performance
648 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700649 // Contact shortcuts need a different set of flags to be launched now
650 // The updateContactsShortcuts change is idempotent, so we can keep using it like
651 // back in the Donut days
652 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700653 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700654 }
655
Adam Cohendcd297f2013-06-18 13:13:40 -0700656 if (version < 13) {
657 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
658 // to persist workspace screens and their relative order.
659 mMaxScreenId = 0;
660
661 // This will never happen in the wild, but when we switch to using workspace
662 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700663 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700664
665 addWorkspacesTable(db);
666 version = 13;
667 }
668
Chris Wrend5e66bf2013-09-16 14:02:29 -0400669 if (version < 14) {
670 db.beginTransaction();
671 try {
672 // Insert new column for holding widget provider name
673 db.execSQL("ALTER TABLE favorites " +
674 "ADD COLUMN appWidgetProvider TEXT;");
675 db.setTransactionSuccessful();
676 version = 14;
677 } catch (SQLException ex) {
678 // Old version remains, which means we wipe old data
679 Log.e(TAG, ex.getMessage(), ex);
680 } finally {
681 db.endTransaction();
682 }
683 }
684
Chris Wren1ada10d2013-09-13 18:01:38 -0400685
686 if (version < 15) {
687 db.beginTransaction();
688 try {
689 // Insert new column for holding update timestamp
690 db.execSQL("ALTER TABLE favorites " +
691 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
692 db.execSQL("ALTER TABLE workspaceScreens " +
693 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
694 db.setTransactionSuccessful();
695 version = 15;
696 } catch (SQLException ex) {
697 // Old version remains, which means we wipe old data
698 Log.e(TAG, ex.getMessage(), ex);
699 } finally {
700 db.endTransaction();
701 }
702 }
703
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800704 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800705 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800706 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700707 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
708
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800709 onCreate(db);
710 }
711 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800712
713 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800714 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
715 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
716
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700717 Cursor c = null;
718 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800719 db.beginTransaction();
720 try {
721 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700722 c = db.query(TABLE_FAVORITES,
723 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800724 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700725 if (c == null) return false;
726
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800727 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700728
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800729 final int idIndex = c.getColumnIndex(Favorites._ID);
730 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700731
732 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800733 long favoriteId = c.getLong(idIndex);
734 final String intentUri = c.getString(intentIndex);
735 if (intentUri != null) {
736 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700737 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800738 android.util.Log.d("Home", intent.toString());
739 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700740 if (uri != null) {
741 final String data = uri.toString();
742 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
743 actionQuickContact.equals(intent.getAction())) &&
744 (data.startsWith("content://contacts/people/") ||
745 data.startsWith("content://com.android.contacts/" +
746 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800747
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700748 final Intent newIntent = new Intent(actionQuickContact);
749 // When starting from the launcher, start in a new, cleared task
750 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
751 // clear the whole thing preemptively here since
752 // QuickContactActivity will finish itself when launching other
753 // detail activities.
754 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
755 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700756 newIntent.putExtra(
757 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700758 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700759 // Determine the type and also put that in the shortcut
760 // (that can speed up launch a bit)
761 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800762
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700763 final ContentValues values = new ContentValues();
764 values.put(LauncherSettings.Favorites.INTENT,
765 newIntent.toUri(0));
766
767 String updateWhere = Favorites._ID + "=" + favoriteId;
768 db.update(TABLE_FAVORITES, values, updateWhere, null);
769 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800770 }
771 } catch (RuntimeException ex) {
772 Log.e(TAG, "Problem upgrading shortcut", ex);
773 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700774 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800775 }
776 }
777 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700778
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800779 db.setTransactionSuccessful();
780 } catch (SQLException ex) {
781 Log.w(TAG, "Problem while upgrading contacts", ex);
782 return false;
783 } finally {
784 db.endTransaction();
785 if (c != null) {
786 c.close();
787 }
788 }
789
790 return true;
791 }
792
Joe Onorato0589f0f2010-02-08 13:44:00 -0800793 private void normalizeIcons(SQLiteDatabase db) {
794 Log.d(TAG, "normalizing icons");
795
Joe Onorato346e1292010-02-18 10:34:24 -0500796 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800797 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400798 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800799 try {
800 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400801 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600802 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800803
804 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
805 Favorites.ICON_TYPE_BITMAP, null);
806
807 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
808 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
809
810 while (c.moveToNext()) {
811 long id = c.getLong(idIndex);
812 byte[] data = c.getBlob(iconIndex);
813 try {
814 Bitmap bitmap = Utilities.resampleIconBitmap(
815 BitmapFactory.decodeByteArray(data, 0, data.length),
816 mContext);
817 if (bitmap != null) {
818 update.bindLong(1, id);
819 data = ItemInfo.flattenBitmap(bitmap);
820 if (data != null) {
821 update.bindBlob(2, data);
822 update.execute();
823 }
824 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800825 }
826 } catch (Exception e) {
827 if (!logged) {
828 Log.e(TAG, "Failed normalizing icon " + id, e);
829 } else {
830 Log.e(TAG, "Also failed normalizing icon " + id);
831 }
832 logged = true;
833 }
834 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000835 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800836 } catch (SQLException ex) {
837 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
838 } finally {
839 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400840 if (update != null) {
841 update.close();
842 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800843 if (c != null) {
844 c.close();
845 }
846 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700847 }
848
849 // Generates a new ID to use for an object in your database. This method should be only
850 // called from the main UI thread. As an exception, we do call it when we call the
851 // constructor from the worker thread; however, this doesn't extend until after the
852 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
853 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 public long generateNewItemId() {
855 if (mMaxItemId < 0) {
856 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700857 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700858 mMaxItemId += 1;
859 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700860 }
861
Winson Chungc763c4e2013-07-19 13:49:06 -0700862 public void updateMaxItemId(long id) {
863 mMaxItemId = id + 1;
864 }
865
Adam Cohendcd297f2013-06-18 13:13:40 -0700866 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700867 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
868
869 // get the result
870 final int maxIdIndex = 0;
871 long id = -1;
872 if (c != null && c.moveToNext()) {
873 id = c.getLong(maxIdIndex);
874 }
Michael Jurka5130e402011-10-13 04:55:35 -0700875 if (c != null) {
876 c.close();
877 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700878
879 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700880 throw new RuntimeException("Error: could not query max item id");
881 }
882
883 return id;
884 }
885
886 // Generates a new ID to use for an workspace screen in your database. This method
887 // should be only called from the main UI thread. As an exception, we do call it when we
888 // call the constructor from the worker thread; however, this doesn't extend until after the
889 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
890 // after that point
891 public long generateNewScreenId() {
892 if (mMaxScreenId < 0) {
893 throw new RuntimeException("Error: max screen id was not initialized");
894 }
895 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800896 // Log to disk
897 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700898 return mMaxScreenId;
899 }
900
901 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800902 // Log to disk
903 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700904 mMaxScreenId = maxScreenId;
905 }
906
907 private long initializeMaxScreenId(SQLiteDatabase db) {
908 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
909
910 // get the result
911 final int maxIdIndex = 0;
912 long id = -1;
913 if (c != null && c.moveToNext()) {
914 id = c.getLong(maxIdIndex);
915 }
916 if (c != null) {
917 c.close();
918 }
919
920 if (id == -1) {
921 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700922 }
923
Winson Chunga90303b2013-11-15 13:05:06 -0800924 // Log to disk
925 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700926 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800927 }
928
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800929 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700930 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +0000931 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800932 */
933 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +0000934 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800935 final int[] bindSources = new int[] {
936 Favorites.ITEM_TYPE_WIDGET_CLOCK,
937 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +0000938 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800939 };
Bjorn Bringert7984c942009-12-09 15:38:25 +0000940
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800941 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700942
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700944
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 db.beginTransaction();
946 try {
947 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +0000948 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800949 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700950
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800951 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700952
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800953 final ContentValues values = new ContentValues();
954 while (c != null && c.moveToNext()) {
955 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +0000956 int favoriteType = c.getInt(1);
957
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700958 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800959 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700960 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700961
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800962 if (LOGD) {
963 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
964 + " for favoriteId=" + favoriteId);
965 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +0000967 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
968 values.put(Favorites.APPWIDGET_ID, appWidgetId);
969
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800970 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +0000971 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
972 values.put(LauncherSettings.Favorites.SPANX, 4);
973 values.put(LauncherSettings.Favorites.SPANY, 1);
974 } else {
975 values.put(LauncherSettings.Favorites.SPANX, 2);
976 values.put(LauncherSettings.Favorites.SPANY, 2);
977 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800978
979 String updateWhere = Favorites._ID + "=" + favoriteId;
980 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +0000981
Bjorn Bringert34251342009-12-15 13:33:11 +0000982 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700983 // TODO: check return value
984 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000985 new ComponentName("com.android.alarmclock",
986 "com.android.alarmclock.AnalogAppWidgetProvider"));
987 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700988 // TODO: check return value
989 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +0000990 new ComponentName("com.android.camera",
991 "com.android.camera.PhotoAppWidgetProvider"));
992 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700993 // TODO: check return value
994 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +0000995 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +0000996 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800997 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800998 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800999 }
1000 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001001
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001002 db.setTransactionSuccessful();
1003 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001004 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001005 } finally {
1006 db.endTransaction();
1007 if (c != null) {
1008 c.close();
1009 }
1010 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001011
1012 // Update max item id
1013 mMaxItemId = initializeMaxItemId(db);
1014 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 }
1016
Michael Jurka8b805b12012-04-18 14:23:14 -07001017 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1018 throws XmlPullParserException, IOException {
1019 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001020 while ((type = parser.next()) != XmlPullParser.START_TAG
1021 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001022 ;
1023 }
1024
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001025 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001026 throw new XmlPullParserException("No start tag found");
1027 }
1028
1029 if (!parser.getName().equals(firstElementName)) {
1030 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1031 ", expected " + firstElementName);
1032 }
1033 }
1034
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001035 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001036 * Loads the default set of favorite packages from an xml file.
1037 *
1038 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001039 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001040 */
Winson Chung6d092682011-11-16 18:43:26 -08001041 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001042 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1043 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1044 ContentValues values = new ContentValues();
1045
Daniel Sandler57dac262013-10-03 13:28:36 -04001046 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1047
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001048 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001049 int i = 0;
1050 try {
Winson Chung6d092682011-11-16 18:43:26 -08001051 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001052 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001053 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001054
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001055 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001056
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001057 int type;
1058 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1059 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1060
1061 if (type != XmlPullParser.START_TAG) {
1062 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001063 }
1064
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001065 boolean added = false;
1066 final String name = parser.getName();
1067
Daniel Sandler57dac262013-10-03 13:28:36 -04001068 if (TAG_INCLUDE.equals(name)) {
1069 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1070
1071 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1072
1073 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1074 "", resId));
1075
1076 if (resId != 0 && resId != workspaceResourceId) {
1077 // recursively load some more favorites, why not?
1078 i += loadFavorites(db, resId);
1079 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001080 } else {
1081 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1082 }
1083
1084 a.recycle();
1085
1086 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1087 continue;
1088 }
1089
1090 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001091 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1092
Winson Chung3d503fb2011-07-13 17:25:49 -07001093 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1094 if (a.hasValue(R.styleable.Favorite_container)) {
1095 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1096 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001097
Winson Chung6d092682011-11-16 18:43:26 -08001098 String screen = a.getString(R.styleable.Favorite_screen);
1099 String x = a.getString(R.styleable.Favorite_x);
1100 String y = a.getString(R.styleable.Favorite_y);
1101
Winson Chung6d092682011-11-16 18:43:26 -08001102 values.clear();
1103 values.put(LauncherSettings.Favorites.CONTAINER, container);
1104 values.put(LauncherSettings.Favorites.SCREEN, screen);
1105 values.put(LauncherSettings.Favorites.CELLX, x);
1106 values.put(LauncherSettings.Favorites.CELLY, y);
1107
Daniel Sandler57dac262013-10-03 13:28:36 -04001108 if (LOGD) {
1109 final String title = a.getString(R.styleable.Favorite_title);
1110 final String pkg = a.getString(R.styleable.Favorite_packageName);
1111 final String something = title != null ? title : pkg;
1112 Log.v(TAG, String.format(
1113 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1114 "", name,
1115 (something == null ? "" : (" \"" + something + "\"")),
1116 container, screen, x, y));
1117 }
1118
Winson Chung6d092682011-11-16 18:43:26 -08001119 if (TAG_FAVORITE.equals(name)) {
1120 long id = addAppShortcut(db, values, a, packageManager, intent);
1121 added = id >= 0;
1122 } else if (TAG_SEARCH.equals(name)) {
1123 added = addSearchWidget(db, values);
1124 } else if (TAG_CLOCK.equals(name)) {
1125 added = addClockWidget(db, values);
1126 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001127 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001128 } else if (TAG_SHORTCUT.equals(name)) {
1129 long id = addUriShortcut(db, values, a);
1130 added = id >= 0;
1131 } else if (TAG_FOLDER.equals(name)) {
1132 String title;
1133 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1134 if (titleResId != -1) {
1135 title = mContext.getResources().getString(titleResId);
1136 } else {
1137 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001138 }
Winson Chung6d092682011-11-16 18:43:26 -08001139 values.put(LauncherSettings.Favorites.TITLE, title);
1140 long folderId = addFolder(db, values);
1141 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001142
Winson Chung6d092682011-11-16 18:43:26 -08001143 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001144
Winson Chung6d092682011-11-16 18:43:26 -08001145 int folderDepth = parser.getDepth();
1146 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1147 parser.getDepth() > folderDepth) {
1148 if (type != XmlPullParser.START_TAG) {
1149 continue;
1150 }
1151 final String folder_item_name = parser.getName();
1152
1153 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1154 R.styleable.Favorite);
1155 values.clear();
1156 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1157
Daniel Sandler57dac262013-10-03 13:28:36 -04001158 if (LOGD) {
1159 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1160 final String uri = ar.getString(R.styleable.Favorite_uri);
1161 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1162 folder_item_name, uri != null ? uri : pkg));
1163 }
1164
Winson Chung6d092682011-11-16 18:43:26 -08001165 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1166 long id =
1167 addAppShortcut(db, values, ar, packageManager, intent);
1168 if (id >= 0) {
1169 folderItems.add(id);
1170 }
1171 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1172 long id = addUriShortcut(db, values, ar);
1173 if (id >= 0) {
1174 folderItems.add(id);
1175 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001176 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001177 throw new RuntimeException("Folders can " +
1178 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001179 }
Winson Chung6d092682011-11-16 18:43:26 -08001180 ar.recycle();
1181 }
1182 // We can only have folders with >= 2 items, so we need to remove the
1183 // folder and clean up if less than 2 items were included, or some
1184 // failed to add, and less than 2 were actually added
1185 if (folderItems.size() < 2 && folderId >= 0) {
1186 // We just delete the folder and any items that made it
1187 deleteId(db, folderId);
1188 if (folderItems.size() > 0) {
1189 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001190 }
Winson Chung6d092682011-11-16 18:43:26 -08001191 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001192 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001194 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001195 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001196 }
1197 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001198 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001199 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001200 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001201 } catch (RuntimeException e) {
1202 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001203 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001204
Winson Chungc763c4e2013-07-19 13:49:06 -07001205 // Update the max item id after we have loaded the database
1206 if (mMaxItemId == -1) {
1207 mMaxItemId = initializeMaxItemId(db);
1208 }
1209
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001210 return i;
1211 }
1212
Adam Cohen228da5a2011-07-27 22:23:47 -07001213 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001214 PackageManager packageManager, Intent intent) {
Adam Cohen228da5a2011-07-27 22:23:47 -07001215 long id = -1;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001216 ActivityInfo info;
1217 String packageName = a.getString(R.styleable.Favorite_packageName);
1218 String className = a.getString(R.styleable.Favorite_className);
1219 try {
Romain Guy693599f2010-03-23 10:58:18 -07001220 ComponentName cn;
1221 try {
1222 cn = new ComponentName(packageName, className);
1223 info = packageManager.getActivityInfo(cn, 0);
1224 } catch (PackageManager.NameNotFoundException nnfe) {
1225 String[] packages = packageManager.currentToCanonicalPackageNames(
1226 new String[] { packageName });
1227 cn = new ComponentName(packages[0], className);
1228 info = packageManager.getActivityInfo(cn, 0);
1229 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001230 id = generateNewItemId();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001231 intent.setComponent(cn);
Romain Guy693599f2010-03-23 10:58:18 -07001232 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1233 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Romain Guy1ce1a242009-06-23 17:34:54 -07001234 values.put(Favorites.INTENT, intent.toUri(0));
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001235 values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
1236 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1237 values.put(Favorites.SPANX, 1);
1238 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001239 values.put(Favorites._ID, generateNewItemId());
Adam Cohen228da5a2011-07-27 22:23:47 -07001240 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1241 return -1;
1242 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001243 } catch (PackageManager.NameNotFoundException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001244 Log.w(TAG, "Unable to add favorite: " + packageName +
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001245 "/" + className, e);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001246 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001247 return id;
1248 }
1249
1250 private long addFolder(SQLiteDatabase db, ContentValues values) {
1251 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1252 values.put(Favorites.SPANX, 1);
1253 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001254 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001255 values.put(Favorites._ID, id);
1256 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1257 return -1;
1258 } else {
1259 return id;
1260 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001261 }
1262
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001263 private ComponentName getSearchWidgetProvider() {
1264 SearchManager searchManager =
1265 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1266 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1267 if (searchComponent == null) return null;
1268 return getProviderInPackage(searchComponent.getPackageName());
1269 }
1270
1271 /**
1272 * Gets an appwidget provider from the given package. If the package contains more than
1273 * one appwidget provider, an arbitrary one is returned.
1274 */
1275 private ComponentName getProviderInPackage(String packageName) {
1276 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1277 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1278 if (providers == null) return null;
1279 final int providerCount = providers.size();
1280 for (int i = 0; i < providerCount; i++) {
1281 ComponentName provider = providers.get(i).provider;
1282 if (provider != null && provider.getPackageName().equals(packageName)) {
1283 return provider;
1284 }
1285 }
1286 return null;
1287 }
1288
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001289 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001290 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001291 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001292 }
1293
1294 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001295 ComponentName cn = new ComponentName("com.android.alarmclock",
1296 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001297 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001298 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001299
Winson Chungb3302ae2012-05-01 10:19:14 -07001300 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1301 SQLiteDatabase db, ContentValues values, TypedArray a,
1302 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001303
Mike Cleronb87bd162009-10-30 16:36:56 -07001304 String packageName = a.getString(R.styleable.Favorite_packageName);
1305 String className = a.getString(R.styleable.Favorite_className);
1306
1307 if (packageName == null || className == null) {
1308 return false;
1309 }
Romain Guy693599f2010-03-23 10:58:18 -07001310
1311 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001312 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001313 try {
1314 packageManager.getReceiverInfo(cn, 0);
1315 } catch (Exception e) {
1316 String[] packages = packageManager.currentToCanonicalPackageNames(
1317 new String[] { packageName });
1318 cn = new ComponentName(packages[0], className);
1319 try {
1320 packageManager.getReceiverInfo(cn, 0);
1321 } catch (Exception e1) {
1322 hasPackage = false;
1323 }
1324 }
1325
1326 if (hasPackage) {
1327 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1328 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001329
1330 // Read the extras
1331 Bundle extras = new Bundle();
1332 int widgetDepth = parser.getDepth();
1333 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1334 parser.getDepth() > widgetDepth) {
1335 if (type != XmlPullParser.START_TAG) {
1336 continue;
1337 }
1338
1339 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1340 if (TAG_EXTRA.equals(parser.getName())) {
1341 String key = ar.getString(R.styleable.Extra_key);
1342 String value = ar.getString(R.styleable.Extra_value);
1343 if (key != null && value != null) {
1344 extras.putString(key, value);
1345 } else {
1346 throw new RuntimeException("Widget extras must have a key and value");
1347 }
1348 } else {
1349 throw new RuntimeException("Widgets can contain only extras");
1350 }
1351 ar.recycle();
1352 }
1353
1354 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001355 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001356
Romain Guy693599f2010-03-23 10:58:18 -07001357 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001358 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001359 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001360 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001361 boolean allocatedAppWidgets = false;
1362 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1363
1364 try {
1365 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001366
Mike Cleronb87bd162009-10-30 16:36:56 -07001367 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001368 values.put(Favorites.SPANX, spanX);
1369 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001370 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001371 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001372 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001373 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001374
1375 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001376
Michael Jurka8b805b12012-04-18 14:23:14 -07001377 // TODO: need to check return value
1378 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001379
1380 // Send a broadcast to configure the widget
1381 if (extras != null && !extras.isEmpty()) {
1382 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1383 intent.setComponent(cn);
1384 intent.putExtras(extras);
1385 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1386 mContext.sendBroadcast(intent);
1387 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001388 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001389 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001390 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001391
Mike Cleronb87bd162009-10-30 16:36:56 -07001392 return allocatedAppWidgets;
1393 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001394
1395 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001396 TypedArray a) {
1397 Resources r = mContext.getResources();
1398
1399 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1400 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1401
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001402 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001403 String uri = null;
1404 try {
1405 uri = a.getString(R.styleable.Favorite_uri);
1406 intent = Intent.parseUri(uri, 0);
1407 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001408 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001409 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001410 }
1411
1412 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001413 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001414 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001415 }
1416
Adam Cohendcd297f2013-06-18 13:13:40 -07001417 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001418 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1419 values.put(Favorites.INTENT, intent.toUri(0));
1420 values.put(Favorites.TITLE, r.getString(titleResId));
1421 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1422 values.put(Favorites.SPANX, 1);
1423 values.put(Favorites.SPANY, 1);
1424 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1425 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1426 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001427 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001428
Adam Cohen228da5a2011-07-27 22:23:47 -07001429 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1430 return -1;
1431 }
1432 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001433 }
1434 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001435
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001436 /**
1437 * Build a query string that will match any row where the column matches
1438 * anything in the values list.
1439 */
1440 static String buildOrWhereString(String column, int[] values) {
1441 StringBuilder selectWhere = new StringBuilder();
1442 for (int i = values.length - 1; i >= 0; i--) {
1443 selectWhere.append(column).append("=").append(values[i]);
1444 if (i > 0) {
1445 selectWhere.append(" OR ");
1446 }
1447 }
1448 return selectWhere.toString();
1449 }
1450
1451 static class SqlArguments {
1452 public final String table;
1453 public final String where;
1454 public final String[] args;
1455
1456 SqlArguments(Uri url, String where, String[] args) {
1457 if (url.getPathSegments().size() == 1) {
1458 this.table = url.getPathSegments().get(0);
1459 this.where = where;
1460 this.args = args;
1461 } else if (url.getPathSegments().size() != 2) {
1462 throw new IllegalArgumentException("Invalid URI: " + url);
1463 } else if (!TextUtils.isEmpty(where)) {
1464 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1465 } else {
1466 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001467 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001468 this.args = null;
1469 }
1470 }
1471
1472 SqlArguments(Uri url) {
1473 if (url.getPathSegments().size() == 1) {
1474 table = url.getPathSegments().get(0);
1475 where = null;
1476 args = null;
1477 } else {
1478 throw new IllegalArgumentException("Invalid URI: " + url);
1479 }
1480 }
1481 }
1482}