blob: a5f5690dec163c307faabfdfd40463aabf3affdd [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000019import android.app.SearchManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000022import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080023import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070024import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000025import android.content.ContentProviderOperation;
26import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000032import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070033import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ActivityInfo;
Jason Monk41314972014-03-03 16:11:30 -050035import android.content.pm.ApplicationInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.content.pm.PackageManager;
Jason Monk41314972014-03-03 16:11:30 -050037import android.content.pm.ResolveInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.database.Cursor;
42import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteDatabase;
44import android.database.sqlite.SQLiteOpenHelper;
45import android.database.sqlite.SQLiteQueryBuilder;
46import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080047import android.graphics.Bitmap;
48import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070049import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070050import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070051import android.provider.Settings;
52import android.text.TextUtils;
53import android.util.AttributeSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080054import android.util.Log;
55import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070056
Daniel Sandler325dc232013-06-05 22:57:57 -040057import com.android.launcher3.LauncherSettings.Favorites;
Chris Wrene523e702013-10-09 10:36:55 -040058import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
60import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
62
Dan Sandlerd5024042014-01-09 15:01:33 -050063import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070065import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070066import java.util.ArrayList;
Dan Sandlerd5024042014-01-09 15:01:33 -050067import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000068import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080071 private static final String TAG = "Launcher.LauncherProvider";
72 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
74 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070075
Adam Cohen71e03b92014-02-21 14:09:53 -080076 private static final int DATABASE_VERSION = 17;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Adam Cohene25af792013-06-06 23:08:25 -070078 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040079 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070080
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050081 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050082 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050083
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070085 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070087 static final String UPGRADED_FROM_OLD_DATABASE =
88 "UPGRADED_FROM_OLD_DATABASE";
89 static final String EMPTY_DATABASE_CREATED =
90 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020091 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
92 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Winson Chungb3302ae2012-05-01 10:19:14 -070094 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070095 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070096
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070097 /**
Romain Guy73b979d2009-06-09 12:57:21 -070098 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070099 * {@link AppWidgetHost#deleteHost()} is called during database creation.
100 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
101 */
102 static final Uri CONTENT_APPWIDGET_RESET_URI =
103 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700104
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700105 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700106 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
108 @Override
109 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400110 final Context context = getContext();
111 mOpenHelper = new DatabaseHelper(context);
112 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113 return true;
114 }
115
Winson Chung0b560dd2014-01-21 13:00:26 -0800116 public boolean wasNewDbCreated() {
117 return mOpenHelper.wasNewDbCreated();
118 }
119
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120 @Override
121 public String getType(Uri uri) {
122 SqlArguments args = new SqlArguments(uri, null, null);
123 if (TextUtils.isEmpty(args.where)) {
124 return "vnd.android.cursor.dir/" + args.table;
125 } else {
126 return "vnd.android.cursor.item/" + args.table;
127 }
128 }
129
130 @Override
131 public Cursor query(Uri uri, String[] projection, String selection,
132 String[] selectionArgs, String sortOrder) {
133
134 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
135 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
136 qb.setTables(args.table);
137
Romain Guy73b979d2009-06-09 12:57:21 -0700138 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
140 result.setNotificationUri(getContext().getContentResolver(), uri);
141
142 return result;
143 }
144
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 private static long dbInsertAndCheck(DatabaseHelper helper,
146 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500147 if (values == null) {
148 throw new RuntimeException("Error: attempting to insert null values");
149 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500150 if (!values.containsKey(LauncherSettings.BaseLauncherColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151 throw new RuntimeException("Error: attempting to add item without specifying an id");
152 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500153 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 return db.insert(table, nullColumnHack, values);
155 }
156
Adam Cohen228da5a2011-07-27 22:23:47 -0700157 private static void deleteId(SQLiteDatabase db, long id) {
158 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
159 SqlArguments args = new SqlArguments(uri, null, null);
160 db.delete(args.table, args.where, args.args);
161 }
162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public Uri insert(Uri uri, ContentValues initialValues) {
165 SqlArguments args = new SqlArguments(uri);
166
167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400168 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700169 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 if (rowId <= 0) return null;
171
172 uri = ContentUris.withAppendedId(uri, rowId);
173 sendNotify(uri);
174
175 return uri;
176 }
177
178 @Override
179 public int bulkInsert(Uri uri, ContentValues[] values) {
180 SqlArguments args = new SqlArguments(uri);
181
182 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
183 db.beginTransaction();
184 try {
185 int numValues = values.length;
186 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400187 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700188 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
189 return 0;
190 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 }
192 db.setTransactionSuccessful();
193 } finally {
194 db.endTransaction();
195 }
196
197 sendNotify(uri);
198 return values.length;
199 }
200
201 @Override
Yura085c8532014-02-11 15:15:29 +0000202 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
203 throws OperationApplicationException {
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 db.beginTransaction();
206 try {
207 ContentProviderResult[] result = super.applyBatch(operations);
208 db.setTransactionSuccessful();
209 return result;
210 } finally {
211 db.endTransaction();
212 }
213 }
214
215 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 public int delete(Uri uri, String selection, String[] selectionArgs) {
217 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
218
219 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
220 int count = db.delete(args.table, args.where, args.args);
221 if (count > 0) sendNotify(uri);
222
223 return count;
224 }
225
226 @Override
227 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
228 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
229
Chris Wren1ada10d2013-09-13 18:01:38 -0400230 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
232 int count = db.update(args.table, values, args.where, args.args);
233 if (count > 0) sendNotify(uri);
234
235 return count;
236 }
237
238 private void sendNotify(Uri uri) {
239 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
240 if (notify == null || "true".equals(notify)) {
241 getContext().getContentResolver().notifyChange(uri, null);
242 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400243
244 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400245 LauncherBackupAgentHelper.dataChanged(getContext());
Chris Wren1ada10d2013-09-13 18:01:38 -0400246 }
247
248 private void addModifiedTime(ContentValues values) {
249 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 }
251
Adam Cohendcd297f2013-06-18 13:13:40 -0700252 public long generateNewItemId() {
253 return mOpenHelper.generateNewItemId();
254 }
255
Winson Chungc763c4e2013-07-19 13:49:06 -0700256 public void updateMaxItemId(long id) {
257 mOpenHelper.updateMaxItemId(id);
258 }
259
Adam Cohendcd297f2013-06-18 13:13:40 -0700260 public long generateNewScreenId() {
261 return mOpenHelper.generateNewScreenId();
262 }
263
264 // This is only required one time while loading the workspace during the
265 // upgrade path, and should never be called from anywhere else.
266 public void updateMaxScreenId(long maxScreenId) {
267 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700268 }
269
Brian Muramatsu5524b492012-10-02 16:55:54 -0700270 /**
Adam Cohene25af792013-06-06 23:08:25 -0700271 * @param Should we load the old db for upgrade? first run only.
272 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700273 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400274 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700275 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
276
Winson Chungc763c4e2013-07-19 13:49:06 -0700277 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700278
Winson Chungc763c4e2013-07-19 13:49:06 -0700279 sJustLoadedFromOldDb = false;
280 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700281
282 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700283 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700284 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700285 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700286 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700287 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700288 }
289
290 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700291 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
292 */
Michael Jurka45355c42012-10-08 13:21:35 +0200293 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400294 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700295 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700296
Winson Chungc763c4e2013-07-19 13:49:06 -0700297 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500298 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200299 int workspaceResId = origWorkspaceResId;
300
Brian Muramatsu5524b492012-10-02 16:55:54 -0700301 // Use default workspace resource if none provided
302 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800303 workspaceResId =
304 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700305 }
306
Michael Jurkab85f8a42012-04-25 15:48:32 -0700307 // Populate favorites table with initial favorites
308 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700309 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200310 if (origWorkspaceResId != 0) {
311 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
312 }
Adam Cohene25af792013-06-06 23:08:25 -0700313
Brian Muramatsu5524b492012-10-02 16:55:54 -0700314 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700315 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700316 editor.commit();
317 }
318 }
319
Dan Sandlerd5024042014-01-09 15:01:33 -0500320 public void migrateLauncher2Shortcuts() {
321 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
322 LauncherSettings.Favorites.OLD_CONTENT_URI);
323 }
324
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800325 private static int getDefaultWorkspaceResourceId() {
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800326 if (LauncherAppState.isDisableAllApps()) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800327 return R.xml.default_workspace_no_all_apps;
328 } else {
329 return R.xml.default_workspace;
330 }
331 }
332
Winson Chungc763c4e2013-07-19 13:49:06 -0700333 private static interface ContentValuesCallback {
334 public void onRow(ContentValues values);
335 }
336
Adam Cohen6dbe0492013-12-02 17:00:14 -0800337 private static boolean shouldImportLauncher2Database(Context context) {
338 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
339
340 // We don't import the old databse for tablets, as the grid size has changed.
341 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
342 }
343
Dan Sandlerd5024042014-01-09 15:01:33 -0500344 public void deleteDatabase() {
345 // Are you sure? (y/n)
346 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500347 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500348 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500349 if (dbFile.exists()) {
350 SQLiteDatabase.deleteDatabase(dbFile);
351 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500352 mOpenHelper = new DatabaseHelper(getContext());
353 }
354
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500356 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 private static final String TAG_FAVORITES = "favorites";
358 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700359 private static final String TAG_CLOCK = "clock";
360 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700361 private static final String TAG_APPWIDGET = "appwidget";
362 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700363 private static final String TAG_FOLDER = "folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700364 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400365 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700366
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800367 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700368 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700369 private long mMaxItemId = -1;
370 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800371
Winson Chung0b560dd2014-01-21 13:00:26 -0800372 private boolean mNewDbCreated = false;
373
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800374 DatabaseHelper(Context context) {
375 super(context, DATABASE_NAME, null, DATABASE_VERSION);
376 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700377 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700378
379 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
380 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700381 if (mMaxItemId == -1) {
382 mMaxItemId = initializeMaxItemId(getWritableDatabase());
383 }
384 if (mMaxScreenId == -1) {
385 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700386 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800387 }
388
Winson Chung0b560dd2014-01-21 13:00:26 -0800389 public boolean wasNewDbCreated() {
390 return mNewDbCreated;
391 }
392
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700393 /**
394 * Send notification that we've deleted the {@link AppWidgetHost},
395 * probably as part of the initial database creation. The receiver may
396 * want to re-call {@link AppWidgetHost#startListening()} to ensure
397 * callbacks are correctly set.
398 */
399 private void sendAppWidgetResetNotify() {
400 final ContentResolver resolver = mContext.getContentResolver();
401 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
402 }
403
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800404 @Override
405 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800406 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700407
Adam Cohendcd297f2013-06-18 13:13:40 -0700408 mMaxItemId = 1;
409 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800410 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700411
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800412 db.execSQL("CREATE TABLE favorites (" +
413 "_id INTEGER PRIMARY KEY," +
414 "title TEXT," +
415 "intent TEXT," +
416 "container INTEGER," +
417 "screen INTEGER," +
418 "cellX INTEGER," +
419 "cellY INTEGER," +
420 "spanX INTEGER," +
421 "spanY INTEGER," +
422 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700423 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800424 "isShortcut INTEGER," +
425 "iconType INTEGER," +
426 "iconPackage TEXT," +
427 "iconResource TEXT," +
428 "icon BLOB," +
429 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400430 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400431 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500432 "modified INTEGER NOT NULL DEFAULT 0," +
433 "restored INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800434 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700435 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800436
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700437 // Database was just created, so wipe any previous widgets
438 if (mAppWidgetHost != null) {
439 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700440 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800441 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700442
Adam Cohen6dbe0492013-12-02 17:00:14 -0800443 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500444 // Try converting the old database
445 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
446 public void onRow(ContentValues values) {
447 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
448 if (container == Favorites.CONTAINER_DESKTOP) {
449 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
450 screen = (int) upgradeLauncherDb_permuteScreens(screen);
451 values.put(LauncherSettings.Favorites.SCREEN, screen);
452 }
453 }
454 };
455 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
456 "/old_favorites?notify=true");
457 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
458 // Try and upgrade from the Launcher2 db
459 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
460 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
461 // If we fail, then set a flag to load the default workspace
462 setFlagEmptyDbCreated();
463 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700464 }
465 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500466 // Right now, in non-default workspace cases, we want to run the final
467 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
468 // set that flag too.
469 setFlagJustLoadedOldDb();
470 } else {
471 // Fresh and clean launcher DB.
472 mMaxItemId = initializeMaxItemId(db);
473 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474 }
475 }
476
Adam Cohendcd297f2013-06-18 13:13:40 -0700477 private void addWorkspacesTable(SQLiteDatabase db) {
478 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
479 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400480 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
481 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700482 ");");
483 }
484
Winson Chungc763c4e2013-07-19 13:49:06 -0700485 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400486 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700487 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
488 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700489 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
490 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700491 editor.commit();
492 }
493
Winson Chungc763c4e2013-07-19 13:49:06 -0700494 private void setFlagEmptyDbCreated() {
495 String spKey = LauncherAppState.getSharedPreferencesKey();
496 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
497 SharedPreferences.Editor editor = sp.edit();
498 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
499 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
500 editor.commit();
501 }
502
503 // We rearrange the screens from the old launcher
504 // 12345 -> 34512
505 private long upgradeLauncherDb_permuteScreens(long screen) {
506 if (screen >= 2) {
507 return screen - 2;
508 } else {
509 return screen + 3;
510 }
511 }
512
513 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
514 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800515 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800516 boolean converted = false;
517
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 final ContentResolver resolver = mContext.getContentResolver();
519 Cursor cursor = null;
520
521 try {
522 cursor = resolver.query(uri, null, null, null, null);
523 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700524 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800525 }
526
527 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700528 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800529 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700530 if (cursor.getCount() > 0) {
531 converted = copyFromCursor(db, cursor, cb) > 0;
532 if (converted && deleteRows) {
533 resolver.delete(uri, null, null);
534 }
535 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800536 } finally {
537 cursor.close();
538 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800539 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700540
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800541 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700542 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800543 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800544 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700545
546 // Update max item id
547 mMaxItemId = initializeMaxItemId(db);
548 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549 }
550
551 return converted;
552 }
553
Winson Chungc763c4e2013-07-19 13:49:06 -0700554 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700555 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800556 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
557 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
558 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
559 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
560 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
561 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
562 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
563 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
564 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
565 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
566 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
567 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
568 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
569
570 ContentValues[] rows = new ContentValues[c.getCount()];
571 int i = 0;
572 while (c.moveToNext()) {
573 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700574 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
576 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
577 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
578 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
579 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
580 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
581 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
582 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700583 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
585 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
586 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
587 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
588 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700589 if (cb != null) {
590 cb.onRow(values);
591 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800592 rows[i++] = values;
593 }
594
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800595 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700596 if (i > 0) {
597 db.beginTransaction();
598 try {
599 int numValues = rows.length;
600 for (i = 0; i < numValues; i++) {
601 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
602 return 0;
603 } else {
604 total++;
605 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700607 db.setTransactionSuccessful();
608 } finally {
609 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
612
613 return total;
614 }
615
616 @Override
617 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700618 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700619
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700621 if (version < 3) {
622 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 db.beginTransaction();
624 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700625 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800626 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700627 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700629 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 } catch (SQLException ex) {
631 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800632 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 } finally {
634 db.endTransaction();
635 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700636
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700638 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 convertWidgets(db);
640 }
641 }
Romain Guy73b979d2009-06-09 12:57:21 -0700642
643 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800644 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700645 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700646
Romain Guy509cd6a2010-03-23 15:10:56 -0700647 // Where's version 5?
648 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400649 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700650 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
651 // but version 5 on there was the updateContactsShortcuts change
652 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
653 // The updateContactsShortcuts change is idempotent, so running it twice
654 // is okay so we'll do that when upgrading the devices that shipped with it.
655 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800656 // We went from 3 to 5 screens. Move everything 1 to the right
657 db.beginTransaction();
658 try {
659 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
660 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800661 } catch (SQLException ex) {
662 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800663 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800664 } finally {
665 db.endTransaction();
666 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700667
Romain Guy509cd6a2010-03-23 15:10:56 -0700668 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800669 if (updateContactsShortcuts(db)) {
670 version = 6;
671 }
672 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000673
674 if (version < 7) {
675 // Version 7 gets rid of the special search widget.
676 convertWidgets(db);
677 version = 7;
678 }
679
Joe Onorato0589f0f2010-02-08 13:44:00 -0800680 if (version < 8) {
681 // Version 8 (froyo) has the icons all normalized. This should
682 // already be the case in practice, but we now rely on it and don't
683 // resample the images each time.
684 normalizeIcons(db);
685 version = 8;
686 }
687
Winson Chung3d503fb2011-07-13 17:25:49 -0700688 if (version < 9) {
689 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
690 // 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 -0700691 if (mMaxItemId == -1) {
692 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700693 }
694
695 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800696 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700697 version = 9;
698 }
699
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700700 // We bumped the version three time during JB, once to update the launch flags, once to
701 // update the override for the default launch animation and once to set the mimetype
702 // to improve startup performance
703 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700704 // Contact shortcuts need a different set of flags to be launched now
705 // The updateContactsShortcuts change is idempotent, so we can keep using it like
706 // back in the Donut days
707 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700708 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700709 }
710
Adam Cohendcd297f2013-06-18 13:13:40 -0700711 if (version < 13) {
712 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
713 // to persist workspace screens and their relative order.
714 mMaxScreenId = 0;
715
716 // This will never happen in the wild, but when we switch to using workspace
717 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700718 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700719
720 addWorkspacesTable(db);
721 version = 13;
722 }
723
Chris Wrend5e66bf2013-09-16 14:02:29 -0400724 if (version < 14) {
725 db.beginTransaction();
726 try {
727 // Insert new column for holding widget provider name
728 db.execSQL("ALTER TABLE favorites " +
729 "ADD COLUMN appWidgetProvider TEXT;");
730 db.setTransactionSuccessful();
731 version = 14;
732 } catch (SQLException ex) {
733 // Old version remains, which means we wipe old data
734 Log.e(TAG, ex.getMessage(), ex);
735 } finally {
736 db.endTransaction();
737 }
738 }
739
Chris Wren1ada10d2013-09-13 18:01:38 -0400740 if (version < 15) {
741 db.beginTransaction();
742 try {
743 // Insert new column for holding update timestamp
744 db.execSQL("ALTER TABLE favorites " +
745 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
746 db.execSQL("ALTER TABLE workspaceScreens " +
747 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
748 db.setTransactionSuccessful();
749 version = 15;
750 } catch (SQLException ex) {
751 // Old version remains, which means we wipe old data
752 Log.e(TAG, ex.getMessage(), ex);
753 } finally {
754 db.endTransaction();
755 }
756 }
757
Chris Wrenf4d08112014-01-16 18:13:56 -0500758
759 if (version < 16) {
760 db.beginTransaction();
761 try {
762 // Insert new column for holding restore status
763 db.execSQL("ALTER TABLE favorites " +
764 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
765 db.setTransactionSuccessful();
766 version = 16;
767 } catch (SQLException ex) {
768 // Old version remains, which means we wipe old data
769 Log.e(TAG, ex.getMessage(), ex);
770 } finally {
771 db.endTransaction();
772 }
773 }
774
Adam Cohen71e03b92014-02-21 14:09:53 -0800775 if (version < 17) {
776 // We use the db version upgrade here to identify users who may not have seen
777 // clings yet (because they weren't available), but for whom the clings are now
778 // available (tablet users). Because one of the possible cling flows (migration)
779 // is very destructive (wipes out workspaces), we want to prevent this from showing
780 // until clear data. We do so by marking that the clings have been shown.
781 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
782 version = 17;
783 }
784
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800785 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800786 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800787 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700788 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
789
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800790 onCreate(db);
791 }
792 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800793
794 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800795 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
796 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
797
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700798 Cursor c = null;
799 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800800 db.beginTransaction();
801 try {
802 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700803 c = db.query(TABLE_FAVORITES,
804 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800805 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700806 if (c == null) return false;
807
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800808 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700809
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800810 final int idIndex = c.getColumnIndex(Favorites._ID);
811 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700812
813 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800814 long favoriteId = c.getLong(idIndex);
815 final String intentUri = c.getString(intentIndex);
816 if (intentUri != null) {
817 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700818 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800819 android.util.Log.d("Home", intent.toString());
820 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700821 if (uri != null) {
822 final String data = uri.toString();
823 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
824 actionQuickContact.equals(intent.getAction())) &&
825 (data.startsWith("content://contacts/people/") ||
826 data.startsWith("content://com.android.contacts/" +
827 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800828
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700829 final Intent newIntent = new Intent(actionQuickContact);
830 // When starting from the launcher, start in a new, cleared task
831 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
832 // clear the whole thing preemptively here since
833 // QuickContactActivity will finish itself when launching other
834 // detail activities.
835 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
836 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700837 newIntent.putExtra(
838 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700839 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700840 // Determine the type and also put that in the shortcut
841 // (that can speed up launch a bit)
842 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800843
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700844 final ContentValues values = new ContentValues();
845 values.put(LauncherSettings.Favorites.INTENT,
846 newIntent.toUri(0));
847
848 String updateWhere = Favorites._ID + "=" + favoriteId;
849 db.update(TABLE_FAVORITES, values, updateWhere, null);
850 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800851 }
852 } catch (RuntimeException ex) {
853 Log.e(TAG, "Problem upgrading shortcut", ex);
854 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700855 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800856 }
857 }
858 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700859
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800860 db.setTransactionSuccessful();
861 } catch (SQLException ex) {
862 Log.w(TAG, "Problem while upgrading contacts", ex);
863 return false;
864 } finally {
865 db.endTransaction();
866 if (c != null) {
867 c.close();
868 }
869 }
870
871 return true;
872 }
873
Joe Onorato0589f0f2010-02-08 13:44:00 -0800874 private void normalizeIcons(SQLiteDatabase db) {
875 Log.d(TAG, "normalizing icons");
876
Joe Onorato346e1292010-02-18 10:34:24 -0500877 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800878 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400879 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800880 try {
881 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400882 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600883 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800884
885 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
886 Favorites.ICON_TYPE_BITMAP, null);
887
888 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
889 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
890
891 while (c.moveToNext()) {
892 long id = c.getLong(idIndex);
893 byte[] data = c.getBlob(iconIndex);
894 try {
895 Bitmap bitmap = Utilities.resampleIconBitmap(
896 BitmapFactory.decodeByteArray(data, 0, data.length),
897 mContext);
898 if (bitmap != null) {
899 update.bindLong(1, id);
900 data = ItemInfo.flattenBitmap(bitmap);
901 if (data != null) {
902 update.bindBlob(2, data);
903 update.execute();
904 }
905 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800906 }
907 } catch (Exception e) {
908 if (!logged) {
909 Log.e(TAG, "Failed normalizing icon " + id, e);
910 } else {
911 Log.e(TAG, "Also failed normalizing icon " + id);
912 }
913 logged = true;
914 }
915 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000916 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800917 } catch (SQLException ex) {
918 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
919 } finally {
920 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400921 if (update != null) {
922 update.close();
923 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800924 if (c != null) {
925 c.close();
926 }
927 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700928 }
929
930 // Generates a new ID to use for an object in your database. This method should be only
931 // called from the main UI thread. As an exception, we do call it when we call the
932 // constructor from the worker thread; however, this doesn't extend until after the
933 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
934 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700935 public long generateNewItemId() {
936 if (mMaxItemId < 0) {
937 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700938 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700939 mMaxItemId += 1;
940 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700941 }
942
Winson Chungc763c4e2013-07-19 13:49:06 -0700943 public void updateMaxItemId(long id) {
944 mMaxItemId = id + 1;
945 }
946
Chris Wren5dee7af2013-12-20 17:22:11 -0500947 public void checkId(String table, ContentValues values) {
948 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
949 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
950 mMaxScreenId = Math.max(id, mMaxScreenId);
951 } else {
952 mMaxItemId = Math.max(id, mMaxItemId);
953 }
954 }
955
Adam Cohendcd297f2013-06-18 13:13:40 -0700956 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700957 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
958
959 // get the result
960 final int maxIdIndex = 0;
961 long id = -1;
962 if (c != null && c.moveToNext()) {
963 id = c.getLong(maxIdIndex);
964 }
Michael Jurka5130e402011-10-13 04:55:35 -0700965 if (c != null) {
966 c.close();
967 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700968
969 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700970 throw new RuntimeException("Error: could not query max item id");
971 }
972
973 return id;
974 }
975
976 // Generates a new ID to use for an workspace screen in your database. This method
977 // should be only called from the main UI thread. As an exception, we do call it when we
978 // call the constructor from the worker thread; however, this doesn't extend until after the
979 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
980 // after that point
981 public long generateNewScreenId() {
982 if (mMaxScreenId < 0) {
983 throw new RuntimeException("Error: max screen id was not initialized");
984 }
985 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800986 // Log to disk
987 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 return mMaxScreenId;
989 }
990
991 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800992 // Log to disk
993 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 mMaxScreenId = maxScreenId;
995 }
996
997 private long initializeMaxScreenId(SQLiteDatabase db) {
998 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
999
1000 // get the result
1001 final int maxIdIndex = 0;
1002 long id = -1;
1003 if (c != null && c.moveToNext()) {
1004 id = c.getLong(maxIdIndex);
1005 }
1006 if (c != null) {
1007 c.close();
1008 }
1009
1010 if (id == -1) {
1011 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001012 }
1013
Winson Chunga90303b2013-11-15 13:05:06 -08001014 // Log to disk
1015 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001016 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001017 }
1018
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001019 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001020 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001021 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001022 */
1023 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001024 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001025 final int[] bindSources = new int[] {
1026 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1027 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001028 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001029 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001030
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001031 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001032
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001033 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001034
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001035 db.beginTransaction();
1036 try {
1037 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001038 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001039 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001040
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001041 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001042
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001043 final ContentValues values = new ContentValues();
1044 while (c != null && c.moveToNext()) {
1045 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001046 int favoriteType = c.getInt(1);
1047
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001048 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001049 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001050 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001051
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001052 if (LOGD) {
1053 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1054 + " for favoriteId=" + favoriteId);
1055 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001056 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001057 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1058 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1059
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001060 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001061 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1062 values.put(LauncherSettings.Favorites.SPANX, 4);
1063 values.put(LauncherSettings.Favorites.SPANY, 1);
1064 } else {
1065 values.put(LauncherSettings.Favorites.SPANX, 2);
1066 values.put(LauncherSettings.Favorites.SPANY, 2);
1067 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001068
1069 String updateWhere = Favorites._ID + "=" + favoriteId;
1070 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001071
Bjorn Bringert34251342009-12-15 13:33:11 +00001072 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001073 // TODO: check return value
1074 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001075 new ComponentName("com.android.alarmclock",
1076 "com.android.alarmclock.AnalogAppWidgetProvider"));
1077 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001078 // TODO: check return value
1079 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001080 new ComponentName("com.android.camera",
1081 "com.android.camera.PhotoAppWidgetProvider"));
1082 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001083 // TODO: check return value
1084 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001085 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001086 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001087 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001088 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001089 }
1090 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001091
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001092 db.setTransactionSuccessful();
1093 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001094 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001095 } finally {
1096 db.endTransaction();
1097 if (c != null) {
1098 c.close();
1099 }
1100 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001101
1102 // Update max item id
1103 mMaxItemId = initializeMaxItemId(db);
1104 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001105 }
1106
Michael Jurka8b805b12012-04-18 14:23:14 -07001107 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1108 throws XmlPullParserException, IOException {
1109 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001110 while ((type = parser.next()) != XmlPullParser.START_TAG
1111 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001112 ;
1113 }
1114
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001115 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001116 throw new XmlPullParserException("No start tag found");
1117 }
1118
1119 if (!parser.getName().equals(firstElementName)) {
1120 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1121 ", expected " + firstElementName);
1122 }
1123 }
1124
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001125 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001126 * Loads the default set of favorite packages from an xml file.
1127 *
1128 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001129 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001130 */
Winson Chung6d092682011-11-16 18:43:26 -08001131 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001132 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1133 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1134 ContentValues values = new ContentValues();
1135
Daniel Sandler57dac262013-10-03 13:28:36 -04001136 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001139 int i = 0;
1140 try {
Winson Chung6d092682011-11-16 18:43:26 -08001141 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001142 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001143 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001144
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001145 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001146
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001147 int type;
1148 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1149 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1150
1151 if (type != XmlPullParser.START_TAG) {
1152 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001153 }
1154
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001155 boolean added = false;
1156 final String name = parser.getName();
1157
Daniel Sandler57dac262013-10-03 13:28:36 -04001158 if (TAG_INCLUDE.equals(name)) {
1159 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1160
1161 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1162
1163 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1164 "", resId));
1165
1166 if (resId != 0 && resId != workspaceResourceId) {
1167 // recursively load some more favorites, why not?
1168 i += loadFavorites(db, resId);
1169 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001170 } else {
1171 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1172 }
1173
1174 a.recycle();
1175
1176 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1177 continue;
1178 }
1179
1180 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001181 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1182
Winson Chung3d503fb2011-07-13 17:25:49 -07001183 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1184 if (a.hasValue(R.styleable.Favorite_container)) {
1185 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1186 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001187
Winson Chung6d092682011-11-16 18:43:26 -08001188 String screen = a.getString(R.styleable.Favorite_screen);
1189 String x = a.getString(R.styleable.Favorite_x);
1190 String y = a.getString(R.styleable.Favorite_y);
1191
Winson Chung6d092682011-11-16 18:43:26 -08001192 values.clear();
1193 values.put(LauncherSettings.Favorites.CONTAINER, container);
1194 values.put(LauncherSettings.Favorites.SCREEN, screen);
1195 values.put(LauncherSettings.Favorites.CELLX, x);
1196 values.put(LauncherSettings.Favorites.CELLY, y);
1197
Daniel Sandler57dac262013-10-03 13:28:36 -04001198 if (LOGD) {
1199 final String title = a.getString(R.styleable.Favorite_title);
1200 final String pkg = a.getString(R.styleable.Favorite_packageName);
1201 final String something = title != null ? title : pkg;
1202 Log.v(TAG, String.format(
1203 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1204 "", name,
1205 (something == null ? "" : (" \"" + something + "\"")),
1206 container, screen, x, y));
1207 }
1208
Winson Chung6d092682011-11-16 18:43:26 -08001209 if (TAG_FAVORITE.equals(name)) {
1210 long id = addAppShortcut(db, values, a, packageManager, intent);
1211 added = id >= 0;
1212 } else if (TAG_SEARCH.equals(name)) {
1213 added = addSearchWidget(db, values);
1214 } else if (TAG_CLOCK.equals(name)) {
1215 added = addClockWidget(db, values);
1216 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001217 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001218 } else if (TAG_SHORTCUT.equals(name)) {
1219 long id = addUriShortcut(db, values, a);
1220 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001221 } else if (TAG_RESOLVE.equals(name)) {
1222 // This looks through the contained favorites (or meta-favorites) and
1223 // attempts to add them as shortcuts in the fallback group's location
1224 // until one is added successfully.
1225 added = false;
1226 final int groupDepth = parser.getDepth();
1227 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1228 parser.getDepth() > groupDepth) {
1229 if (type != XmlPullParser.START_TAG) {
1230 continue;
1231 }
1232 final String fallback_item_name = parser.getName();
1233 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1234 R.styleable.Favorite);
1235 if (!added) {
1236 if (TAG_FAVORITE.equals(fallback_item_name)) {
1237 final long id =
1238 addAppShortcut(db, values, ar, packageManager, intent);
1239 added = id >= 0;
1240 } else {
1241 Log.e(TAG, "Fallback groups can contain only favorites "
1242 + ar.toString());
1243 }
1244 }
1245 ar.recycle();
1246 }
Winson Chung6d092682011-11-16 18:43:26 -08001247 } else if (TAG_FOLDER.equals(name)) {
1248 String title;
1249 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1250 if (titleResId != -1) {
1251 title = mContext.getResources().getString(titleResId);
1252 } else {
1253 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001254 }
Winson Chung6d092682011-11-16 18:43:26 -08001255 values.put(LauncherSettings.Favorites.TITLE, title);
1256 long folderId = addFolder(db, values);
1257 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001258
Winson Chung6d092682011-11-16 18:43:26 -08001259 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001260
Winson Chung6d092682011-11-16 18:43:26 -08001261 int folderDepth = parser.getDepth();
1262 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1263 parser.getDepth() > folderDepth) {
1264 if (type != XmlPullParser.START_TAG) {
1265 continue;
1266 }
1267 final String folder_item_name = parser.getName();
1268
1269 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1270 R.styleable.Favorite);
1271 values.clear();
1272 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1273
Daniel Sandler57dac262013-10-03 13:28:36 -04001274 if (LOGD) {
1275 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1276 final String uri = ar.getString(R.styleable.Favorite_uri);
1277 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1278 folder_item_name, uri != null ? uri : pkg));
1279 }
1280
Winson Chung6d092682011-11-16 18:43:26 -08001281 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1282 long id =
1283 addAppShortcut(db, values, ar, packageManager, intent);
1284 if (id >= 0) {
1285 folderItems.add(id);
1286 }
1287 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1288 long id = addUriShortcut(db, values, ar);
1289 if (id >= 0) {
1290 folderItems.add(id);
1291 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001292 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001293 throw new RuntimeException("Folders can " +
1294 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001295 }
Winson Chung6d092682011-11-16 18:43:26 -08001296 ar.recycle();
1297 }
1298 // We can only have folders with >= 2 items, so we need to remove the
1299 // folder and clean up if less than 2 items were included, or some
1300 // failed to add, and less than 2 were actually added
1301 if (folderItems.size() < 2 && folderId >= 0) {
1302 // We just delete the folder and any items that made it
1303 deleteId(db, folderId);
1304 if (folderItems.size() > 0) {
1305 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001306 }
Winson Chung6d092682011-11-16 18:43:26 -08001307 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001308 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001309 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001310 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001311 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001312 }
1313 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001314 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001315 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001316 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001317 } catch (RuntimeException e) {
1318 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001319 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001320
Winson Chungc763c4e2013-07-19 13:49:06 -07001321 // Update the max item id after we have loaded the database
1322 if (mMaxItemId == -1) {
1323 mMaxItemId = initializeMaxItemId(db);
1324 }
1325
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001326 return i;
1327 }
1328
Jason Monk41314972014-03-03 16:11:30 -05001329 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1330 // logical choice for what shortcut should be used for that intent exists, then it is
1331 // added. Otherwise add nothing.
1332 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001333 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001334 final String intentUri = a.getString(R.styleable.Favorite_uri);
1335
1336 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001337 try {
Jason Monk41314972014-03-03 16:11:30 -05001338 metaIntent = Intent.parseUri(intentUri, 0);
1339 } catch (URISyntaxException e) {
1340 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1341 return -1;
1342 }
1343
1344 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1345 PackageManager.MATCH_DEFAULT_ONLY);
1346 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1347 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1348
1349 // Verify that the result is an app and not just the resolver dialog asking which
1350 // app to use.
1351 if (wouldLaunchResolverActivity(resolved, appList)) {
1352 // If only one of the results is a system app then choose that as the default.
1353 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1354 if (systemApp == null) {
1355 // There is no logical choice for this meta-favorite, so rather than making
1356 // a bad choice just add nothing.
1357 Log.w(TAG, "No preference or single system activity found for "
1358 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001359 return -1;
1360 }
Jason Monk41314972014-03-03 16:11:30 -05001361 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001362 }
Jason Monk41314972014-03-03 16:11:30 -05001363 final ActivityInfo info = resolved.activityInfo;
1364 intent.setComponent(new ComponentName(info.packageName, info.name));
1365 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1366 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1367
1368 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1369 }
1370
1371 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1372 PackageManager packageManager) {
1373 ResolveInfo systemResolve = null;
1374 final int N = appList.size();
1375 for (int i = 0; i < N; ++i) {
1376 try {
1377 ApplicationInfo info = packageManager.getApplicationInfo(
1378 appList.get(i).activityInfo.packageName, 0);
1379 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1380 if (systemResolve != null) {
1381 return null;
1382 } else {
1383 systemResolve = appList.get(i);
1384 }
1385 }
1386 } catch (PackageManager.NameNotFoundException e) {
1387 Log.w(TAG, "Unable to get info about resolve results", e);
1388 return null;
1389 }
1390 }
1391 return systemResolve;
1392 }
1393
1394 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1395 List<ResolveInfo> appList) {
1396 // If the list contains the above resolved activity, then it can't be
1397 // ResolverActivity itself.
1398 for (int i = 0; i < appList.size(); ++i) {
1399 ResolveInfo tmp = appList.get(i);
1400 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1401 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1402 return false;
1403 }
1404 }
1405 return true;
1406 }
1407
1408 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1409 PackageManager packageManager, Intent intent) {
1410 if (a.hasValue(R.styleable.Favorite_packageName)
1411 && a.hasValue(R.styleable.Favorite_className)) {
1412 ActivityInfo info;
1413 String packageName = a.getString(R.styleable.Favorite_packageName);
1414 String className = a.getString(R.styleable.Favorite_className);
1415 try {
1416 ComponentName cn;
1417 try {
1418 cn = new ComponentName(packageName, className);
1419 info = packageManager.getActivityInfo(cn, 0);
1420 } catch (PackageManager.NameNotFoundException nnfe) {
1421 String[] packages = packageManager.currentToCanonicalPackageNames(
1422 new String[] { packageName });
1423 cn = new ComponentName(packages[0], className);
1424 info = packageManager.getActivityInfo(cn, 0);
1425 }
1426 intent.setComponent(cn);
1427 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1428 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1429
1430 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1431 intent);
1432 } catch (PackageManager.NameNotFoundException e) {
1433 Log.w(TAG, "Unable to add favorite: " + packageName +
1434 "/" + className, e);
1435 }
1436 return -1;
1437 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1438 // If no component specified try to find a shortcut to add from the URI.
1439 return addAppShortcutByUri(db, values, a, packageManager, intent);
1440 } else {
1441 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1442 return -1;
1443 }
1444 }
1445
1446 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1447 Intent intent) {
1448 long id = generateNewItemId();
1449 values.put(Favorites.INTENT, intent.toUri(0));
1450 values.put(Favorites.TITLE, title);
1451 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1452 values.put(Favorites.SPANX, 1);
1453 values.put(Favorites.SPANY, 1);
1454 values.put(Favorites._ID, id);
1455 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1456 return -1;
1457 } else {
1458 return id;
1459 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001460 }
1461
1462 private long addFolder(SQLiteDatabase db, ContentValues values) {
1463 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1464 values.put(Favorites.SPANX, 1);
1465 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001466 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001467 values.put(Favorites._ID, id);
1468 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1469 return -1;
1470 } else {
1471 return id;
1472 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001473 }
1474
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001475 private ComponentName getSearchWidgetProvider() {
1476 SearchManager searchManager =
1477 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1478 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1479 if (searchComponent == null) return null;
1480 return getProviderInPackage(searchComponent.getPackageName());
1481 }
1482
1483 /**
1484 * Gets an appwidget provider from the given package. If the package contains more than
1485 * one appwidget provider, an arbitrary one is returned.
1486 */
1487 private ComponentName getProviderInPackage(String packageName) {
1488 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1489 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1490 if (providers == null) return null;
1491 final int providerCount = providers.size();
1492 for (int i = 0; i < providerCount; i++) {
1493 ComponentName provider = providers.get(i).provider;
1494 if (provider != null && provider.getPackageName().equals(packageName)) {
1495 return provider;
1496 }
1497 }
1498 return null;
1499 }
1500
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001501 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001502 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001503 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001504 }
1505
1506 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001507 ComponentName cn = new ComponentName("com.android.alarmclock",
1508 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001509 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001510 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001511
Winson Chungb3302ae2012-05-01 10:19:14 -07001512 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1513 SQLiteDatabase db, ContentValues values, TypedArray a,
1514 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001515
Mike Cleronb87bd162009-10-30 16:36:56 -07001516 String packageName = a.getString(R.styleable.Favorite_packageName);
1517 String className = a.getString(R.styleable.Favorite_className);
1518
1519 if (packageName == null || className == null) {
1520 return false;
1521 }
Romain Guy693599f2010-03-23 10:58:18 -07001522
1523 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001524 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001525 try {
1526 packageManager.getReceiverInfo(cn, 0);
1527 } catch (Exception e) {
1528 String[] packages = packageManager.currentToCanonicalPackageNames(
1529 new String[] { packageName });
1530 cn = new ComponentName(packages[0], className);
1531 try {
1532 packageManager.getReceiverInfo(cn, 0);
1533 } catch (Exception e1) {
1534 hasPackage = false;
1535 }
1536 }
1537
1538 if (hasPackage) {
1539 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1540 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001541
1542 // Read the extras
1543 Bundle extras = new Bundle();
1544 int widgetDepth = parser.getDepth();
1545 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1546 parser.getDepth() > widgetDepth) {
1547 if (type != XmlPullParser.START_TAG) {
1548 continue;
1549 }
1550
1551 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1552 if (TAG_EXTRA.equals(parser.getName())) {
1553 String key = ar.getString(R.styleable.Extra_key);
1554 String value = ar.getString(R.styleable.Extra_value);
1555 if (key != null && value != null) {
1556 extras.putString(key, value);
1557 } else {
1558 throw new RuntimeException("Widget extras must have a key and value");
1559 }
1560 } else {
1561 throw new RuntimeException("Widgets can contain only extras");
1562 }
1563 ar.recycle();
1564 }
1565
1566 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001567 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001568
Romain Guy693599f2010-03-23 10:58:18 -07001569 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001570 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001571 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001572 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001573 boolean allocatedAppWidgets = false;
1574 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1575
1576 try {
1577 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001578
Mike Cleronb87bd162009-10-30 16:36:56 -07001579 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001580 values.put(Favorites.SPANX, spanX);
1581 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001582 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001583 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001584 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001585 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001586
1587 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001588
Michael Jurka8b805b12012-04-18 14:23:14 -07001589 // TODO: need to check return value
1590 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001591
1592 // Send a broadcast to configure the widget
1593 if (extras != null && !extras.isEmpty()) {
1594 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1595 intent.setComponent(cn);
1596 intent.putExtras(extras);
1597 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1598 mContext.sendBroadcast(intent);
1599 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001600 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001601 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001602 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001603
Mike Cleronb87bd162009-10-30 16:36:56 -07001604 return allocatedAppWidgets;
1605 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001606
1607 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001608 TypedArray a) {
1609 Resources r = mContext.getResources();
1610
1611 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1612 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1613
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001614 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001615 String uri = null;
1616 try {
1617 uri = a.getString(R.styleable.Favorite_uri);
1618 intent = Intent.parseUri(uri, 0);
1619 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001620 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001621 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001622 }
1623
1624 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001625 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001626 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001627 }
1628
Adam Cohendcd297f2013-06-18 13:13:40 -07001629 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001630 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1631 values.put(Favorites.INTENT, intent.toUri(0));
1632 values.put(Favorites.TITLE, r.getString(titleResId));
1633 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1634 values.put(Favorites.SPANX, 1);
1635 values.put(Favorites.SPANY, 1);
1636 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1637 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1638 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001639 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001640
Adam Cohen228da5a2011-07-27 22:23:47 -07001641 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1642 return -1;
1643 }
1644 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001645 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001646
1647 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1648 final ContentResolver resolver = mContext.getContentResolver();
1649 Cursor c = null;
1650 int count = 0;
1651 int curScreen = 0;
1652
1653 try {
1654 c = resolver.query(uri, null, null, null, "title ASC");
1655 } catch (Exception e) {
1656 // Ignore
1657 }
1658
Dan Sandlerd5024042014-01-09 15:01:33 -05001659 // We already have a favorites database in the old provider
1660 if (c != null) {
1661 try {
1662 if (c.getCount() > 0) {
1663 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1664 final int intentIndex
1665 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1666 final int titleIndex
1667 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1668 final int iconTypeIndex
1669 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1670 final int iconIndex
1671 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1672 final int iconPackageIndex
1673 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1674 final int iconResourceIndex
1675 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1676 final int containerIndex
1677 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1678 final int itemTypeIndex
1679 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1680 final int screenIndex
1681 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1682 final int cellXIndex
1683 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1684 final int cellYIndex
1685 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1686 final int uriIndex
1687 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1688 final int displayModeIndex
1689 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1690
1691 int i = 0;
1692 int curX = 0;
1693 int curY = 0;
1694
1695 final LauncherAppState app = LauncherAppState.getInstance();
1696 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1697 final int width = (int) grid.numColumns;
1698 final int height = (int) grid.numRows;
1699 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001700 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001701
1702 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1703
Adam Cohen72960972014-01-15 18:13:55 -08001704 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1705 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001706
1707 while (c.moveToNext()) {
1708 final int itemType = c.getInt(itemTypeIndex);
1709 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1710 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1711 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1712 continue;
1713 }
1714
1715 final int cellX = c.getInt(cellXIndex);
1716 final int cellY = c.getInt(cellYIndex);
1717 final int screen = c.getInt(screenIndex);
1718 int container = c.getInt(containerIndex);
1719 final String intentStr = c.getString(intentIndex);
1720 Launcher.addDumpLog(TAG, "migrating \""
1721 + c.getString(titleIndex) + "\": " + intentStr, true);
1722
1723 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001724
1725 final Intent intent;
1726 final ComponentName cn;
1727 try {
1728 intent = Intent.parseUri(intentStr, 0);
1729 } catch (URISyntaxException e) {
1730 // bogus intent?
1731 Launcher.addDumpLog(TAG,
1732 "skipping invalid intent uri", true);
1733 continue;
1734 }
1735
1736 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001737 if (TextUtils.isEmpty(intentStr)) {
1738 // no intent? no icon
1739 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1740 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001741 } else if (cn != null &&
1742 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001743 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001744 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001745 "no longer exists.", true);
1746 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001747 } else if (container ==
1748 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1749 // Dedupe icons directly on the workspace
1750
Adam Cohen556f6132014-01-15 15:18:08 -08001751 // Canonicalize
1752 // the Play Store sets the package parameter, but Launcher
1753 // does not, so we clear that out to keep them the same
1754 intent.setPackage(null);
1755 final String key = intent.toUri(0);
1756 if (seenIntents.contains(key)) {
1757 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001758 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001759 } else {
1760 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001761 }
1762 }
1763 }
1764
1765 ContentValues values = new ContentValues(c.getColumnCount());
1766 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1767 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1768 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1769 values.put(LauncherSettings.Favorites.ICON_TYPE,
1770 c.getInt(iconTypeIndex));
1771 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1772 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1773 c.getString(iconPackageIndex));
1774 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1775 c.getString(iconResourceIndex));
1776 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1777 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1778 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1779 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1780 c.getInt(displayModeIndex));
1781
1782 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
Adam Cohen72960972014-01-15 18:13:55 -08001783 && (screen >= hotseatWidth ||
1784 screen == grid.hotseatAllAppsRank)) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001785 // no room for you in the hotseat? it's off to the desktop with you
1786 container = Favorites.CONTAINER_DESKTOP;
1787 }
1788
1789 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1790 // In a folder or in the hotseat, preserve position
1791 values.put(LauncherSettings.Favorites.SCREEN, screen);
1792 values.put(LauncherSettings.Favorites.CELLX, cellX);
1793 values.put(LauncherSettings.Favorites.CELLY, cellY);
1794 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001795 // For items contained directly on one of the workspace screen,
1796 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001797 }
1798
1799 values.put(LauncherSettings.Favorites.CONTAINER, container);
1800
Adam Cohen72960972014-01-15 18:13:55 -08001801 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1802 shortcuts.add(values);
1803 } else {
1804 folders.add(values);
1805 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001806 }
1807
Adam Cohen72960972014-01-15 18:13:55 -08001808 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1809 // Folders first
1810 allItems.addAll(folders);
1811 // Then shortcuts
1812 allItems.addAll(shortcuts);
1813
1814 // Layout all the folders
1815 for (ContentValues values: allItems) {
1816 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1817 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1818 // Hotseat items and folder items have already had their
1819 // location information set. Nothing to be done here.
1820 continue;
1821 }
1822 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1823 values.put(LauncherSettings.Favorites.CELLX, curX);
1824 values.put(LauncherSettings.Favorites.CELLY, curY);
1825 curX = (curX + 1) % width;
1826 if (curX == 0) {
1827 curY = (curY + 1);
1828 }
1829 // Leave the last row of icons blank on every screen
1830 if (curY == height - 1) {
1831 curScreen = (int) generateNewScreenId();
1832 curY = 0;
1833 }
1834 }
1835
1836 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001837 db.beginTransaction();
1838 try {
Adam Cohen72960972014-01-15 18:13:55 -08001839 for (ContentValues row: allItems) {
1840 if (row == null) continue;
1841 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001842 < 0) {
1843 return;
1844 } else {
1845 count++;
1846 }
1847 }
1848 db.setTransactionSuccessful();
1849 } finally {
1850 db.endTransaction();
1851 }
1852 }
1853
1854 db.beginTransaction();
1855 try {
1856 for (i=0; i<=curScreen; i++) {
1857 final ContentValues values = new ContentValues();
1858 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1859 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1860 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1861 < 0) {
1862 return;
1863 }
1864 }
1865 db.setTransactionSuccessful();
1866 } finally {
1867 db.endTransaction();
1868 }
1869 }
1870 } finally {
1871 c.close();
1872 }
1873 }
1874
1875 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1876 + (curScreen+1) + " screens", true);
1877
1878 // ensure that new screens are created to hold these icons
1879 setFlagJustLoadedOldDb();
1880
1881 // Update max IDs; very important since we just grabbed IDs from another database
1882 mMaxItemId = initializeMaxItemId(db);
1883 mMaxScreenId = initializeMaxScreenId(db);
1884 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1885 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001886 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001887
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001888 /**
1889 * Build a query string that will match any row where the column matches
1890 * anything in the values list.
1891 */
1892 static String buildOrWhereString(String column, int[] values) {
1893 StringBuilder selectWhere = new StringBuilder();
1894 for (int i = values.length - 1; i >= 0; i--) {
1895 selectWhere.append(column).append("=").append(values[i]);
1896 if (i > 0) {
1897 selectWhere.append(" OR ");
1898 }
1899 }
1900 return selectWhere.toString();
1901 }
1902
1903 static class SqlArguments {
1904 public final String table;
1905 public final String where;
1906 public final String[] args;
1907
1908 SqlArguments(Uri url, String where, String[] args) {
1909 if (url.getPathSegments().size() == 1) {
1910 this.table = url.getPathSegments().get(0);
1911 this.where = where;
1912 this.args = args;
1913 } else if (url.getPathSegments().size() != 2) {
1914 throw new IllegalArgumentException("Invalid URI: " + url);
1915 } else if (!TextUtils.isEmpty(where)) {
1916 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1917 } else {
1918 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001919 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001920 this.args = null;
1921 }
1922 }
1923
1924 SqlArguments(Uri url) {
1925 if (url.getPathSegments().size() == 1) {
1926 table = url.getPathSegments().get(0);
1927 where = null;
1928 args = null;
1929 } else {
1930 throw new IllegalArgumentException("Invalid URI: " + url);
1931 }
1932 }
1933 }
Adam Cohen72960972014-01-15 18:13:55 -08001934}