blob: e9e35958a87308ba227de1905bda060030fcc610 [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;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050055import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070057
Daniel Sandler325dc232013-06-05 22:57:57 -040058import com.android.launcher3.LauncherSettings.Favorites;
Chris Wrene523e702013-10-09 10:36:55 -040059import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070060
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070066import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070067import java.util.ArrayList;
Dan Sandlerd5024042014-01-09 15:01:33 -050068import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000069import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080072 private static final String TAG = "Launcher.LauncherProvider";
73 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
75 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070076
Adam Cohen71e03b92014-02-21 14:09:53 -080077 private static final int DATABASE_VERSION = 17;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Adam Cohene25af792013-06-06 23:08:25 -070079 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040080 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070081
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050082 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050083 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050084
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070086 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070088 static final String UPGRADED_FROM_OLD_DATABASE =
89 "UPGRADED_FROM_OLD_DATABASE";
90 static final String EMPTY_DATABASE_CREATED =
91 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020092 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
93 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Winson Chungb3302ae2012-05-01 10:19:14 -070095 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070096 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -070097
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070098 /**
Romain Guy73b979d2009-06-09 12:57:21 -070099 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700100 * {@link AppWidgetHost#deleteHost()} is called during database creation.
101 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
102 */
103 static final Uri CONTENT_APPWIDGET_RESET_URI =
104 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700105
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700106 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700107 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108
109 @Override
110 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400111 final Context context = getContext();
112 mOpenHelper = new DatabaseHelper(context);
113 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114 return true;
115 }
116
Winson Chung0b560dd2014-01-21 13:00:26 -0800117 public boolean wasNewDbCreated() {
118 return mOpenHelper.wasNewDbCreated();
119 }
120
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 @Override
122 public String getType(Uri uri) {
123 SqlArguments args = new SqlArguments(uri, null, null);
124 if (TextUtils.isEmpty(args.where)) {
125 return "vnd.android.cursor.dir/" + args.table;
126 } else {
127 return "vnd.android.cursor.item/" + args.table;
128 }
129 }
130
131 @Override
132 public Cursor query(Uri uri, String[] projection, String selection,
133 String[] selectionArgs, String sortOrder) {
134
135 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
136 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
137 qb.setTables(args.table);
138
Romain Guy73b979d2009-06-09 12:57:21 -0700139 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
141 result.setNotificationUri(getContext().getContentResolver(), uri);
142
143 return result;
144 }
145
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700146 private static long dbInsertAndCheck(DatabaseHelper helper,
147 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500148 if (values == null) {
149 throw new RuntimeException("Error: attempting to insert null values");
150 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500151 if (!values.containsKey(LauncherSettings.BaseLauncherColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 throw new RuntimeException("Error: attempting to add item without specifying an id");
153 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500154 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 return db.insert(table, nullColumnHack, values);
156 }
157
Adam Cohen228da5a2011-07-27 22:23:47 -0700158 private static void deleteId(SQLiteDatabase db, long id) {
159 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
160 SqlArguments args = new SqlArguments(uri, null, null);
161 db.delete(args.table, args.where, args.args);
162 }
163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 @Override
165 public Uri insert(Uri uri, ContentValues initialValues) {
166 SqlArguments args = new SqlArguments(uri);
167
168 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400169 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700170 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171 if (rowId <= 0) return null;
172
173 uri = ContentUris.withAppendedId(uri, rowId);
174 sendNotify(uri);
175
176 return uri;
177 }
178
179 @Override
180 public int bulkInsert(Uri uri, ContentValues[] values) {
181 SqlArguments args = new SqlArguments(uri);
182
183 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
184 db.beginTransaction();
185 try {
186 int numValues = values.length;
187 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400188 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700189 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
190 return 0;
191 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 }
193 db.setTransactionSuccessful();
194 } finally {
195 db.endTransaction();
196 }
197
198 sendNotify(uri);
199 return values.length;
200 }
201
202 @Override
Yura085c8532014-02-11 15:15:29 +0000203 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
204 throws OperationApplicationException {
205 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
206 db.beginTransaction();
207 try {
208 ContentProviderResult[] result = super.applyBatch(operations);
209 db.setTransactionSuccessful();
210 return result;
211 } finally {
212 db.endTransaction();
213 }
214 }
215
216 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 public int delete(Uri uri, String selection, String[] selectionArgs) {
218 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
219
220 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
221 int count = db.delete(args.table, args.where, args.args);
222 if (count > 0) sendNotify(uri);
223
224 return count;
225 }
226
227 @Override
228 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
229 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
230
Chris Wren1ada10d2013-09-13 18:01:38 -0400231 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
233 int count = db.update(args.table, values, args.where, args.args);
234 if (count > 0) sendNotify(uri);
235
236 return count;
237 }
238
239 private void sendNotify(Uri uri) {
240 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
241 if (notify == null || "true".equals(notify)) {
242 getContext().getContentResolver().notifyChange(uri, null);
243 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400244
245 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400246 LauncherBackupAgentHelper.dataChanged(getContext());
Chris Wren1ada10d2013-09-13 18:01:38 -0400247 }
248
249 private void addModifiedTime(ContentValues values) {
250 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800251 }
252
Adam Cohendcd297f2013-06-18 13:13:40 -0700253 public long generateNewItemId() {
254 return mOpenHelper.generateNewItemId();
255 }
256
Winson Chungc763c4e2013-07-19 13:49:06 -0700257 public void updateMaxItemId(long id) {
258 mOpenHelper.updateMaxItemId(id);
259 }
260
Adam Cohendcd297f2013-06-18 13:13:40 -0700261 public long generateNewScreenId() {
262 return mOpenHelper.generateNewScreenId();
263 }
264
265 // This is only required one time while loading the workspace during the
266 // upgrade path, and should never be called from anywhere else.
267 public void updateMaxScreenId(long maxScreenId) {
268 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700269 }
270
Brian Muramatsu5524b492012-10-02 16:55:54 -0700271 /**
Adam Cohene25af792013-06-06 23:08:25 -0700272 * @param Should we load the old db for upgrade? first run only.
273 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700274 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400275 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700276 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
277
Winson Chungc763c4e2013-07-19 13:49:06 -0700278 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700279
Winson Chungc763c4e2013-07-19 13:49:06 -0700280 sJustLoadedFromOldDb = false;
281 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700282
283 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700284 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700285 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700286 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700287 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700288 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700289 }
290
291 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700292 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
293 */
Michael Jurka45355c42012-10-08 13:21:35 +0200294 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400295 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700296 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700297
Winson Chungc763c4e2013-07-19 13:49:06 -0700298 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500299 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200300 int workspaceResId = origWorkspaceResId;
301
Brian Muramatsu5524b492012-10-02 16:55:54 -0700302 // Use default workspace resource if none provided
303 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800304 workspaceResId =
305 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700306 }
307
Michael Jurkab85f8a42012-04-25 15:48:32 -0700308 // Populate favorites table with initial favorites
309 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700310 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200311 if (origWorkspaceResId != 0) {
312 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
313 }
Adam Cohene25af792013-06-06 23:08:25 -0700314
Brian Muramatsu5524b492012-10-02 16:55:54 -0700315 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700316 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700317 editor.commit();
318 }
319 }
320
Dan Sandlerd5024042014-01-09 15:01:33 -0500321 public void migrateLauncher2Shortcuts() {
322 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
323 LauncherSettings.Favorites.OLD_CONTENT_URI);
324 }
325
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800326 private static int getDefaultWorkspaceResourceId() {
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800327 if (LauncherAppState.isDisableAllApps()) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800328 return R.xml.default_workspace_no_all_apps;
329 } else {
330 return R.xml.default_workspace;
331 }
332 }
333
Winson Chungc763c4e2013-07-19 13:49:06 -0700334 private static interface ContentValuesCallback {
335 public void onRow(ContentValues values);
336 }
337
Adam Cohen6dbe0492013-12-02 17:00:14 -0800338 private static boolean shouldImportLauncher2Database(Context context) {
339 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
340
341 // We don't import the old databse for tablets, as the grid size has changed.
342 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
343 }
344
Dan Sandlerd5024042014-01-09 15:01:33 -0500345 public void deleteDatabase() {
346 // Are you sure? (y/n)
347 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500348 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500349 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500350 if (dbFile.exists()) {
351 SQLiteDatabase.deleteDatabase(dbFile);
352 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500353 mOpenHelper = new DatabaseHelper(getContext());
354 }
355
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500357 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800358 private static final String TAG_FAVORITES = "favorites";
359 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700360 private static final String TAG_CLOCK = "clock";
361 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700362 private static final String TAG_APPWIDGET = "appwidget";
363 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700364 private static final String TAG_FOLDER = "folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700365 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400366 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700367
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700369 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700370 private long mMaxItemId = -1;
371 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800372
Winson Chung0b560dd2014-01-21 13:00:26 -0800373 private boolean mNewDbCreated = false;
374
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800375 DatabaseHelper(Context context) {
376 super(context, DATABASE_NAME, null, DATABASE_VERSION);
377 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700378 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700379
380 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
381 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700382 if (mMaxItemId == -1) {
383 mMaxItemId = initializeMaxItemId(getWritableDatabase());
384 }
385 if (mMaxScreenId == -1) {
386 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700387 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800388 }
389
Winson Chung0b560dd2014-01-21 13:00:26 -0800390 public boolean wasNewDbCreated() {
391 return mNewDbCreated;
392 }
393
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700394 /**
395 * Send notification that we've deleted the {@link AppWidgetHost},
396 * probably as part of the initial database creation. The receiver may
397 * want to re-call {@link AppWidgetHost#startListening()} to ensure
398 * callbacks are correctly set.
399 */
400 private void sendAppWidgetResetNotify() {
401 final ContentResolver resolver = mContext.getContentResolver();
402 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
403 }
404
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800405 @Override
406 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800407 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700408
Adam Cohendcd297f2013-06-18 13:13:40 -0700409 mMaxItemId = 1;
410 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800411 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700412
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800413 db.execSQL("CREATE TABLE favorites (" +
414 "_id INTEGER PRIMARY KEY," +
415 "title TEXT," +
416 "intent TEXT," +
417 "container INTEGER," +
418 "screen INTEGER," +
419 "cellX INTEGER," +
420 "cellY INTEGER," +
421 "spanX INTEGER," +
422 "spanY INTEGER," +
423 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700424 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 "isShortcut INTEGER," +
426 "iconType INTEGER," +
427 "iconPackage TEXT," +
428 "iconResource TEXT," +
429 "icon BLOB," +
430 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400431 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400432 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500433 "modified INTEGER NOT NULL DEFAULT 0," +
434 "restored INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800435 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700436 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800437
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700438 // Database was just created, so wipe any previous widgets
439 if (mAppWidgetHost != null) {
440 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700441 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800442 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700443
Adam Cohen6dbe0492013-12-02 17:00:14 -0800444 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500445 // Try converting the old database
446 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
447 public void onRow(ContentValues values) {
448 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
449 if (container == Favorites.CONTAINER_DESKTOP) {
450 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
451 screen = (int) upgradeLauncherDb_permuteScreens(screen);
452 values.put(LauncherSettings.Favorites.SCREEN, screen);
453 }
454 }
455 };
456 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
457 "/old_favorites?notify=true");
458 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
459 // Try and upgrade from the Launcher2 db
460 uri = LauncherSettings.Favorites.OLD_CONTENT_URI;
461 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
462 // If we fail, then set a flag to load the default workspace
463 setFlagEmptyDbCreated();
464 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700465 }
466 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500467 // Right now, in non-default workspace cases, we want to run the final
468 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
469 // set that flag too.
470 setFlagJustLoadedOldDb();
471 } else {
472 // Fresh and clean launcher DB.
473 mMaxItemId = initializeMaxItemId(db);
474 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800475 }
476 }
477
Adam Cohendcd297f2013-06-18 13:13:40 -0700478 private void addWorkspacesTable(SQLiteDatabase db) {
479 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
480 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400481 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
482 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700483 ");");
484 }
485
Winson Chungc763c4e2013-07-19 13:49:06 -0700486 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400487 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700488 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
489 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700490 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
491 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700492 editor.commit();
493 }
494
Winson Chungc763c4e2013-07-19 13:49:06 -0700495 private void setFlagEmptyDbCreated() {
496 String spKey = LauncherAppState.getSharedPreferencesKey();
497 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
498 SharedPreferences.Editor editor = sp.edit();
499 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
500 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
501 editor.commit();
502 }
503
504 // We rearrange the screens from the old launcher
505 // 12345 -> 34512
506 private long upgradeLauncherDb_permuteScreens(long screen) {
507 if (screen >= 2) {
508 return screen - 2;
509 } else {
510 return screen + 3;
511 }
512 }
513
514 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
515 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800516 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800517 boolean converted = false;
518
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800519 final ContentResolver resolver = mContext.getContentResolver();
520 Cursor cursor = null;
521
522 try {
523 cursor = resolver.query(uri, null, null, null, null);
524 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700525 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800526 }
527
528 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700529 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700531 if (cursor.getCount() > 0) {
532 converted = copyFromCursor(db, cursor, cb) > 0;
533 if (converted && deleteRows) {
534 resolver.delete(uri, null, null);
535 }
536 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800537 } finally {
538 cursor.close();
539 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700541
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700543 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800544 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700546
547 // Update max item id
548 mMaxItemId = initializeMaxItemId(db);
549 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550 }
551
552 return converted;
553 }
554
Winson Chungc763c4e2013-07-19 13:49:06 -0700555 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700556 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800557 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
558 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
559 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
560 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
561 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
562 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
563 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
564 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
565 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
566 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
567 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
568 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
569 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
570
571 ContentValues[] rows = new ContentValues[c.getCount()];
572 int i = 0;
573 while (c.moveToNext()) {
574 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700575 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
577 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
578 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
579 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
580 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
581 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
582 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
583 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700584 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
586 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
587 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
588 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
589 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700590 if (cb != null) {
591 cb.onRow(values);
592 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800593 rows[i++] = values;
594 }
595
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700597 if (i > 0) {
598 db.beginTransaction();
599 try {
600 int numValues = rows.length;
601 for (i = 0; i < numValues; i++) {
602 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
603 return 0;
604 } else {
605 total++;
606 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700608 db.setTransactionSuccessful();
609 } finally {
610 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612 }
613
614 return total;
615 }
616
617 @Override
618 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700619 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700620
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700622 if (version < 3) {
623 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 db.beginTransaction();
625 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700626 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700628 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700630 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631 } catch (SQLException ex) {
632 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800633 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634 } finally {
635 db.endTransaction();
636 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700637
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700639 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 convertWidgets(db);
641 }
642 }
Romain Guy73b979d2009-06-09 12:57:21 -0700643
644 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800645 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700646 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700647
Romain Guy509cd6a2010-03-23 15:10:56 -0700648 // Where's version 5?
649 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400650 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700651 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
652 // but version 5 on there was the updateContactsShortcuts change
653 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
654 // The updateContactsShortcuts change is idempotent, so running it twice
655 // is okay so we'll do that when upgrading the devices that shipped with it.
656 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800657 // We went from 3 to 5 screens. Move everything 1 to the right
658 db.beginTransaction();
659 try {
660 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
661 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800662 } catch (SQLException ex) {
663 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800664 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800665 } finally {
666 db.endTransaction();
667 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700668
Romain Guy509cd6a2010-03-23 15:10:56 -0700669 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800670 if (updateContactsShortcuts(db)) {
671 version = 6;
672 }
673 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000674
675 if (version < 7) {
676 // Version 7 gets rid of the special search widget.
677 convertWidgets(db);
678 version = 7;
679 }
680
Joe Onorato0589f0f2010-02-08 13:44:00 -0800681 if (version < 8) {
682 // Version 8 (froyo) has the icons all normalized. This should
683 // already be the case in practice, but we now rely on it and don't
684 // resample the images each time.
685 normalizeIcons(db);
686 version = 8;
687 }
688
Winson Chung3d503fb2011-07-13 17:25:49 -0700689 if (version < 9) {
690 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
691 // 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 -0700692 if (mMaxItemId == -1) {
693 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700694 }
695
696 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800697 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700698 version = 9;
699 }
700
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700701 // We bumped the version three time during JB, once to update the launch flags, once to
702 // update the override for the default launch animation and once to set the mimetype
703 // to improve startup performance
704 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700705 // Contact shortcuts need a different set of flags to be launched now
706 // The updateContactsShortcuts change is idempotent, so we can keep using it like
707 // back in the Donut days
708 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700709 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700710 }
711
Adam Cohendcd297f2013-06-18 13:13:40 -0700712 if (version < 13) {
713 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
714 // to persist workspace screens and their relative order.
715 mMaxScreenId = 0;
716
717 // This will never happen in the wild, but when we switch to using workspace
718 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700719 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700720
721 addWorkspacesTable(db);
722 version = 13;
723 }
724
Chris Wrend5e66bf2013-09-16 14:02:29 -0400725 if (version < 14) {
726 db.beginTransaction();
727 try {
728 // Insert new column for holding widget provider name
729 db.execSQL("ALTER TABLE favorites " +
730 "ADD COLUMN appWidgetProvider TEXT;");
731 db.setTransactionSuccessful();
732 version = 14;
733 } catch (SQLException ex) {
734 // Old version remains, which means we wipe old data
735 Log.e(TAG, ex.getMessage(), ex);
736 } finally {
737 db.endTransaction();
738 }
739 }
740
Chris Wren1ada10d2013-09-13 18:01:38 -0400741 if (version < 15) {
742 db.beginTransaction();
743 try {
744 // Insert new column for holding update timestamp
745 db.execSQL("ALTER TABLE favorites " +
746 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
747 db.execSQL("ALTER TABLE workspaceScreens " +
748 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
749 db.setTransactionSuccessful();
750 version = 15;
751 } catch (SQLException ex) {
752 // Old version remains, which means we wipe old data
753 Log.e(TAG, ex.getMessage(), ex);
754 } finally {
755 db.endTransaction();
756 }
757 }
758
Chris Wrenf4d08112014-01-16 18:13:56 -0500759
760 if (version < 16) {
761 db.beginTransaction();
762 try {
763 // Insert new column for holding restore status
764 db.execSQL("ALTER TABLE favorites " +
765 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
766 db.setTransactionSuccessful();
767 version = 16;
768 } catch (SQLException ex) {
769 // Old version remains, which means we wipe old data
770 Log.e(TAG, ex.getMessage(), ex);
771 } finally {
772 db.endTransaction();
773 }
774 }
775
Adam Cohen71e03b92014-02-21 14:09:53 -0800776 if (version < 17) {
777 // We use the db version upgrade here to identify users who may not have seen
778 // clings yet (because they weren't available), but for whom the clings are now
779 // available (tablet users). Because one of the possible cling flows (migration)
780 // is very destructive (wipes out workspaces), we want to prevent this from showing
781 // until clear data. We do so by marking that the clings have been shown.
782 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
783 version = 17;
784 }
785
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800786 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800787 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800788 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700789 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
790
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 onCreate(db);
792 }
793 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800794
795 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800796 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
797 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
798
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700799 Cursor c = null;
800 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800801 db.beginTransaction();
802 try {
803 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700804 c = db.query(TABLE_FAVORITES,
805 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800806 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700807 if (c == null) return false;
808
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800809 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700810
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800811 final int idIndex = c.getColumnIndex(Favorites._ID);
812 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700813
814 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800815 long favoriteId = c.getLong(idIndex);
816 final String intentUri = c.getString(intentIndex);
817 if (intentUri != null) {
818 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700819 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800820 android.util.Log.d("Home", intent.toString());
821 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700822 if (uri != null) {
823 final String data = uri.toString();
824 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
825 actionQuickContact.equals(intent.getAction())) &&
826 (data.startsWith("content://contacts/people/") ||
827 data.startsWith("content://com.android.contacts/" +
828 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800829
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700830 final Intent newIntent = new Intent(actionQuickContact);
831 // When starting from the launcher, start in a new, cleared task
832 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
833 // clear the whole thing preemptively here since
834 // QuickContactActivity will finish itself when launching other
835 // detail activities.
836 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
837 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700838 newIntent.putExtra(
839 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700840 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700841 // Determine the type and also put that in the shortcut
842 // (that can speed up launch a bit)
843 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800844
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700845 final ContentValues values = new ContentValues();
846 values.put(LauncherSettings.Favorites.INTENT,
847 newIntent.toUri(0));
848
849 String updateWhere = Favorites._ID + "=" + favoriteId;
850 db.update(TABLE_FAVORITES, values, updateWhere, null);
851 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800852 }
853 } catch (RuntimeException ex) {
854 Log.e(TAG, "Problem upgrading shortcut", ex);
855 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700856 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800857 }
858 }
859 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700860
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800861 db.setTransactionSuccessful();
862 } catch (SQLException ex) {
863 Log.w(TAG, "Problem while upgrading contacts", ex);
864 return false;
865 } finally {
866 db.endTransaction();
867 if (c != null) {
868 c.close();
869 }
870 }
871
872 return true;
873 }
874
Joe Onorato0589f0f2010-02-08 13:44:00 -0800875 private void normalizeIcons(SQLiteDatabase db) {
876 Log.d(TAG, "normalizing icons");
877
Joe Onorato346e1292010-02-18 10:34:24 -0500878 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800879 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400880 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800881 try {
882 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400883 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600884 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800885
886 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
887 Favorites.ICON_TYPE_BITMAP, null);
888
889 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
890 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
891
892 while (c.moveToNext()) {
893 long id = c.getLong(idIndex);
894 byte[] data = c.getBlob(iconIndex);
895 try {
896 Bitmap bitmap = Utilities.resampleIconBitmap(
897 BitmapFactory.decodeByteArray(data, 0, data.length),
898 mContext);
899 if (bitmap != null) {
900 update.bindLong(1, id);
901 data = ItemInfo.flattenBitmap(bitmap);
902 if (data != null) {
903 update.bindBlob(2, data);
904 update.execute();
905 }
906 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800907 }
908 } catch (Exception e) {
909 if (!logged) {
910 Log.e(TAG, "Failed normalizing icon " + id, e);
911 } else {
912 Log.e(TAG, "Also failed normalizing icon " + id);
913 }
914 logged = true;
915 }
916 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +0000917 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800918 } catch (SQLException ex) {
919 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
920 } finally {
921 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -0400922 if (update != null) {
923 update.close();
924 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800925 if (c != null) {
926 c.close();
927 }
928 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700929 }
930
931 // Generates a new ID to use for an object in your database. This method should be only
932 // called from the main UI thread. As an exception, we do call it when we call the
933 // constructor from the worker thread; however, this doesn't extend until after the
934 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
935 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -0700936 public long generateNewItemId() {
937 if (mMaxItemId < 0) {
938 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700939 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700940 mMaxItemId += 1;
941 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700942 }
943
Winson Chungc763c4e2013-07-19 13:49:06 -0700944 public void updateMaxItemId(long id) {
945 mMaxItemId = id + 1;
946 }
947
Chris Wren5dee7af2013-12-20 17:22:11 -0500948 public void checkId(String table, ContentValues values) {
949 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
950 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
951 mMaxScreenId = Math.max(id, mMaxScreenId);
952 } else {
953 mMaxItemId = Math.max(id, mMaxItemId);
954 }
955 }
956
Adam Cohendcd297f2013-06-18 13:13:40 -0700957 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700958 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
959
960 // get the result
961 final int maxIdIndex = 0;
962 long id = -1;
963 if (c != null && c.moveToNext()) {
964 id = c.getLong(maxIdIndex);
965 }
Michael Jurka5130e402011-10-13 04:55:35 -0700966 if (c != null) {
967 c.close();
968 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700969
970 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700971 throw new RuntimeException("Error: could not query max item id");
972 }
973
974 return id;
975 }
976
977 // Generates a new ID to use for an workspace screen in your database. This method
978 // should be only called from the main UI thread. As an exception, we do call it when we
979 // call the constructor from the worker thread; however, this doesn't extend until after the
980 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
981 // after that point
982 public long generateNewScreenId() {
983 if (mMaxScreenId < 0) {
984 throw new RuntimeException("Error: max screen id was not initialized");
985 }
986 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800987 // Log to disk
988 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700989 return mMaxScreenId;
990 }
991
992 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800993 // Log to disk
994 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 mMaxScreenId = maxScreenId;
996 }
997
998 private long initializeMaxScreenId(SQLiteDatabase db) {
999 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1000
1001 // get the result
1002 final int maxIdIndex = 0;
1003 long id = -1;
1004 if (c != null && c.moveToNext()) {
1005 id = c.getLong(maxIdIndex);
1006 }
1007 if (c != null) {
1008 c.close();
1009 }
1010
1011 if (id == -1) {
1012 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 }
1014
Winson Chunga90303b2013-11-15 13:05:06 -08001015 // Log to disk
1016 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001018 }
1019
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001020 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001021 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001022 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001023 */
1024 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001025 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001026 final int[] bindSources = new int[] {
1027 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1028 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001029 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001030 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001031
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001032 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001033
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001034 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001035
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001036 db.beginTransaction();
1037 try {
1038 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001039 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001040 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001041
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001042 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001043
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001044 final ContentValues values = new ContentValues();
1045 while (c != null && c.moveToNext()) {
1046 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001047 int favoriteType = c.getInt(1);
1048
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001049 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001050 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001051 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001052
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001053 if (LOGD) {
1054 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1055 + " for favoriteId=" + favoriteId);
1056 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001057 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001058 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1059 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1060
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001061 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001062 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1063 values.put(LauncherSettings.Favorites.SPANX, 4);
1064 values.put(LauncherSettings.Favorites.SPANY, 1);
1065 } else {
1066 values.put(LauncherSettings.Favorites.SPANX, 2);
1067 values.put(LauncherSettings.Favorites.SPANY, 2);
1068 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001069
1070 String updateWhere = Favorites._ID + "=" + favoriteId;
1071 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001072
Bjorn Bringert34251342009-12-15 13:33:11 +00001073 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001074 // TODO: check return value
1075 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001076 new ComponentName("com.android.alarmclock",
1077 "com.android.alarmclock.AnalogAppWidgetProvider"));
1078 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001079 // TODO: check return value
1080 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001081 new ComponentName("com.android.camera",
1082 "com.android.camera.PhotoAppWidgetProvider"));
1083 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001084 // TODO: check return value
1085 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001086 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001087 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001088 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001089 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001090 }
1091 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001092
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001093 db.setTransactionSuccessful();
1094 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001095 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001096 } finally {
1097 db.endTransaction();
1098 if (c != null) {
1099 c.close();
1100 }
1101 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001102
1103 // Update max item id
1104 mMaxItemId = initializeMaxItemId(db);
1105 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001106 }
1107
Michael Jurka8b805b12012-04-18 14:23:14 -07001108 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1109 throws XmlPullParserException, IOException {
1110 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001111 while ((type = parser.next()) != XmlPullParser.START_TAG
1112 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001113 ;
1114 }
1115
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001116 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001117 throw new XmlPullParserException("No start tag found");
1118 }
1119
1120 if (!parser.getName().equals(firstElementName)) {
1121 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1122 ", expected " + firstElementName);
1123 }
1124 }
1125
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001126 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001127 * Loads the default set of favorite packages from an xml file.
1128 *
1129 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001130 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001131 */
Winson Chung6d092682011-11-16 18:43:26 -08001132 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001133 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1134 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1135 ContentValues values = new ContentValues();
1136
Daniel Sandler57dac262013-10-03 13:28:36 -04001137 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1138
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001139 PackageManager packageManager = mContext.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001140 int i = 0;
1141 try {
Winson Chung6d092682011-11-16 18:43:26 -08001142 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001143 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001144 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001145
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001146 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001147
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001148 int type;
1149 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1150 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1151
1152 if (type != XmlPullParser.START_TAG) {
1153 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154 }
1155
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001156 boolean added = false;
1157 final String name = parser.getName();
1158
Daniel Sandler57dac262013-10-03 13:28:36 -04001159 if (TAG_INCLUDE.equals(name)) {
1160 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1161
1162 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1163
1164 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1165 "", resId));
1166
1167 if (resId != 0 && resId != workspaceResourceId) {
1168 // recursively load some more favorites, why not?
1169 i += loadFavorites(db, resId);
1170 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001171 } else {
1172 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1173 }
1174
1175 a.recycle();
1176
1177 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1178 continue;
1179 }
1180
1181 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001182 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1183
Winson Chung3d503fb2011-07-13 17:25:49 -07001184 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1185 if (a.hasValue(R.styleable.Favorite_container)) {
1186 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1187 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001188
Winson Chung6d092682011-11-16 18:43:26 -08001189 String screen = a.getString(R.styleable.Favorite_screen);
1190 String x = a.getString(R.styleable.Favorite_x);
1191 String y = a.getString(R.styleable.Favorite_y);
1192
Winson Chung6d092682011-11-16 18:43:26 -08001193 values.clear();
1194 values.put(LauncherSettings.Favorites.CONTAINER, container);
1195 values.put(LauncherSettings.Favorites.SCREEN, screen);
1196 values.put(LauncherSettings.Favorites.CELLX, x);
1197 values.put(LauncherSettings.Favorites.CELLY, y);
1198
Daniel Sandler57dac262013-10-03 13:28:36 -04001199 if (LOGD) {
1200 final String title = a.getString(R.styleable.Favorite_title);
1201 final String pkg = a.getString(R.styleable.Favorite_packageName);
1202 final String something = title != null ? title : pkg;
1203 Log.v(TAG, String.format(
1204 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1205 "", name,
1206 (something == null ? "" : (" \"" + something + "\"")),
1207 container, screen, x, y));
1208 }
1209
Winson Chung6d092682011-11-16 18:43:26 -08001210 if (TAG_FAVORITE.equals(name)) {
1211 long id = addAppShortcut(db, values, a, packageManager, intent);
1212 added = id >= 0;
1213 } else if (TAG_SEARCH.equals(name)) {
1214 added = addSearchWidget(db, values);
1215 } else if (TAG_CLOCK.equals(name)) {
1216 added = addClockWidget(db, values);
1217 } else if (TAG_APPWIDGET.equals(name)) {
Winson Chungb3302ae2012-05-01 10:19:14 -07001218 added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
Winson Chung6d092682011-11-16 18:43:26 -08001219 } else if (TAG_SHORTCUT.equals(name)) {
1220 long id = addUriShortcut(db, values, a);
1221 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001222 } else if (TAG_RESOLVE.equals(name)) {
1223 // This looks through the contained favorites (or meta-favorites) and
1224 // attempts to add them as shortcuts in the fallback group's location
1225 // until one is added successfully.
1226 added = false;
1227 final int groupDepth = parser.getDepth();
1228 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1229 parser.getDepth() > groupDepth) {
1230 if (type != XmlPullParser.START_TAG) {
1231 continue;
1232 }
1233 final String fallback_item_name = parser.getName();
1234 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1235 R.styleable.Favorite);
1236 if (!added) {
1237 if (TAG_FAVORITE.equals(fallback_item_name)) {
1238 final long id =
1239 addAppShortcut(db, values, ar, packageManager, intent);
1240 added = id >= 0;
1241 } else {
1242 Log.e(TAG, "Fallback groups can contain only favorites "
1243 + ar.toString());
1244 }
1245 }
1246 ar.recycle();
1247 }
Winson Chung6d092682011-11-16 18:43:26 -08001248 } else if (TAG_FOLDER.equals(name)) {
1249 String title;
1250 int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
1251 if (titleResId != -1) {
1252 title = mContext.getResources().getString(titleResId);
1253 } else {
1254 title = mContext.getResources().getString(R.string.folder_name);
Winson Chung3d503fb2011-07-13 17:25:49 -07001255 }
Winson Chung6d092682011-11-16 18:43:26 -08001256 values.put(LauncherSettings.Favorites.TITLE, title);
1257 long folderId = addFolder(db, values);
1258 added = folderId >= 0;
Winson Chung3d503fb2011-07-13 17:25:49 -07001259
Winson Chung6d092682011-11-16 18:43:26 -08001260 ArrayList<Long> folderItems = new ArrayList<Long>();
Winson Chung3d503fb2011-07-13 17:25:49 -07001261
Winson Chung6d092682011-11-16 18:43:26 -08001262 int folderDepth = parser.getDepth();
1263 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1264 parser.getDepth() > folderDepth) {
1265 if (type != XmlPullParser.START_TAG) {
1266 continue;
1267 }
1268 final String folder_item_name = parser.getName();
1269
1270 TypedArray ar = mContext.obtainStyledAttributes(attrs,
1271 R.styleable.Favorite);
1272 values.clear();
1273 values.put(LauncherSettings.Favorites.CONTAINER, folderId);
1274
Daniel Sandler57dac262013-10-03 13:28:36 -04001275 if (LOGD) {
1276 final String pkg = ar.getString(R.styleable.Favorite_packageName);
1277 final String uri = ar.getString(R.styleable.Favorite_uri);
1278 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1279 folder_item_name, uri != null ? uri : pkg));
1280 }
1281
Winson Chung6d092682011-11-16 18:43:26 -08001282 if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
1283 long id =
1284 addAppShortcut(db, values, ar, packageManager, intent);
1285 if (id >= 0) {
1286 folderItems.add(id);
1287 }
1288 } else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
1289 long id = addUriShortcut(db, values, ar);
1290 if (id >= 0) {
1291 folderItems.add(id);
1292 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001293 } else {
Winson Chung6d092682011-11-16 18:43:26 -08001294 throw new RuntimeException("Folders can " +
1295 "contain only shortcuts");
Adam Cohen228da5a2011-07-27 22:23:47 -07001296 }
Winson Chung6d092682011-11-16 18:43:26 -08001297 ar.recycle();
1298 }
1299 // We can only have folders with >= 2 items, so we need to remove the
1300 // folder and clean up if less than 2 items were included, or some
1301 // failed to add, and less than 2 were actually added
1302 if (folderItems.size() < 2 && folderId >= 0) {
1303 // We just delete the folder and any items that made it
1304 deleteId(db, folderId);
1305 if (folderItems.size() > 0) {
1306 deleteId(db, folderItems.get(0));
Adam Cohen228da5a2011-07-27 22:23:47 -07001307 }
Winson Chung6d092682011-11-16 18:43:26 -08001308 added = false;
Winson Chung3d503fb2011-07-13 17:25:49 -07001309 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001310 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001311 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001312 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001313 }
1314 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001315 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001316 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001317 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001318 } catch (RuntimeException e) {
1319 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001320 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001321
Winson Chungc763c4e2013-07-19 13:49:06 -07001322 // Update the max item id after we have loaded the database
1323 if (mMaxItemId == -1) {
1324 mMaxItemId = initializeMaxItemId(db);
1325 }
1326
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001327 return i;
1328 }
1329
Jason Monk41314972014-03-03 16:11:30 -05001330 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1331 // logical choice for what shortcut should be used for that intent exists, then it is
1332 // added. Otherwise add nothing.
1333 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values, TypedArray a,
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001334 PackageManager packageManager, Intent intent) {
Jason Monk41314972014-03-03 16:11:30 -05001335 final String intentUri = a.getString(R.styleable.Favorite_uri);
1336
1337 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001338 try {
Jason Monk41314972014-03-03 16:11:30 -05001339 metaIntent = Intent.parseUri(intentUri, 0);
1340 } catch (URISyntaxException e) {
1341 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1342 return -1;
1343 }
1344
1345 ResolveInfo resolved = packageManager.resolveActivity(metaIntent,
1346 PackageManager.MATCH_DEFAULT_ONLY);
1347 final List<ResolveInfo> appList = packageManager.queryIntentActivities(
1348 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1349
1350 // Verify that the result is an app and not just the resolver dialog asking which
1351 // app to use.
1352 if (wouldLaunchResolverActivity(resolved, appList)) {
1353 // If only one of the results is a system app then choose that as the default.
1354 final ResolveInfo systemApp = getSingleSystemActivity(appList, packageManager);
1355 if (systemApp == null) {
1356 // There is no logical choice for this meta-favorite, so rather than making
1357 // a bad choice just add nothing.
1358 Log.w(TAG, "No preference or single system activity found for "
1359 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001360 return -1;
1361 }
Jason Monk41314972014-03-03 16:11:30 -05001362 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001363 }
Jason Monk41314972014-03-03 16:11:30 -05001364 final ActivityInfo info = resolved.activityInfo;
1365 intent.setComponent(new ComponentName(info.packageName, info.name));
1366 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1367 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1368
1369 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(), intent);
1370 }
1371
1372 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList,
1373 PackageManager packageManager) {
1374 ResolveInfo systemResolve = null;
1375 final int N = appList.size();
1376 for (int i = 0; i < N; ++i) {
1377 try {
1378 ApplicationInfo info = packageManager.getApplicationInfo(
1379 appList.get(i).activityInfo.packageName, 0);
1380 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1381 if (systemResolve != null) {
1382 return null;
1383 } else {
1384 systemResolve = appList.get(i);
1385 }
1386 }
1387 } catch (PackageManager.NameNotFoundException e) {
1388 Log.w(TAG, "Unable to get info about resolve results", e);
1389 return null;
1390 }
1391 }
1392 return systemResolve;
1393 }
1394
1395 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1396 List<ResolveInfo> appList) {
1397 // If the list contains the above resolved activity, then it can't be
1398 // ResolverActivity itself.
1399 for (int i = 0; i < appList.size(); ++i) {
1400 ResolveInfo tmp = appList.get(i);
1401 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1402 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1403 return false;
1404 }
1405 }
1406 return true;
1407 }
1408
1409 private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
1410 PackageManager packageManager, Intent intent) {
1411 if (a.hasValue(R.styleable.Favorite_packageName)
1412 && a.hasValue(R.styleable.Favorite_className)) {
1413 ActivityInfo info;
1414 String packageName = a.getString(R.styleable.Favorite_packageName);
1415 String className = a.getString(R.styleable.Favorite_className);
1416 try {
1417 ComponentName cn;
1418 try {
1419 cn = new ComponentName(packageName, className);
1420 info = packageManager.getActivityInfo(cn, 0);
1421 } catch (PackageManager.NameNotFoundException nnfe) {
1422 String[] packages = packageManager.currentToCanonicalPackageNames(
1423 new String[] { packageName });
1424 cn = new ComponentName(packages[0], className);
1425 info = packageManager.getActivityInfo(cn, 0);
1426 }
1427 intent.setComponent(cn);
1428 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1429 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1430
1431 return addAppShortcut(db, values, info.loadLabel(packageManager).toString(),
1432 intent);
1433 } catch (PackageManager.NameNotFoundException e) {
1434 Log.w(TAG, "Unable to add favorite: " + packageName +
1435 "/" + className, e);
1436 }
1437 return -1;
1438 } else if (a.hasValue(R.styleable.Favorite_uri)) {
1439 // If no component specified try to find a shortcut to add from the URI.
1440 return addAppShortcutByUri(db, values, a, packageManager, intent);
1441 } else {
1442 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1443 return -1;
1444 }
1445 }
1446
1447 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1448 Intent intent) {
1449 long id = generateNewItemId();
1450 values.put(Favorites.INTENT, intent.toUri(0));
1451 values.put(Favorites.TITLE, title);
1452 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1453 values.put(Favorites.SPANX, 1);
1454 values.put(Favorites.SPANY, 1);
1455 values.put(Favorites._ID, id);
1456 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1457 return -1;
1458 } else {
1459 return id;
1460 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001461 }
1462
1463 private long addFolder(SQLiteDatabase db, ContentValues values) {
1464 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1465 values.put(Favorites.SPANX, 1);
1466 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001467 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001468 values.put(Favorites._ID, id);
1469 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1470 return -1;
1471 } else {
1472 return id;
1473 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001474 }
1475
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001476 private ComponentName getSearchWidgetProvider() {
1477 SearchManager searchManager =
1478 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1479 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1480 if (searchComponent == null) return null;
1481 return getProviderInPackage(searchComponent.getPackageName());
1482 }
1483
1484 /**
1485 * Gets an appwidget provider from the given package. If the package contains more than
1486 * one appwidget provider, an arbitrary one is returned.
1487 */
1488 private ComponentName getProviderInPackage(String packageName) {
1489 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1490 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1491 if (providers == null) return null;
1492 final int providerCount = providers.size();
1493 for (int i = 0; i < providerCount; i++) {
1494 ComponentName provider = providers.get(i).provider;
1495 if (provider != null && provider.getPackageName().equals(packageName)) {
1496 return provider;
1497 }
1498 }
1499 return null;
1500 }
1501
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001502 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001503 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001504 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001505 }
1506
1507 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001508 ComponentName cn = new ComponentName("com.android.alarmclock",
1509 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001510 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001511 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001512
Winson Chungb3302ae2012-05-01 10:19:14 -07001513 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
1514 SQLiteDatabase db, ContentValues values, TypedArray a,
1515 PackageManager packageManager) throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001516
Mike Cleronb87bd162009-10-30 16:36:56 -07001517 String packageName = a.getString(R.styleable.Favorite_packageName);
1518 String className = a.getString(R.styleable.Favorite_className);
1519
1520 if (packageName == null || className == null) {
1521 return false;
1522 }
Romain Guy693599f2010-03-23 10:58:18 -07001523
1524 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001525 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001526 try {
1527 packageManager.getReceiverInfo(cn, 0);
1528 } catch (Exception e) {
1529 String[] packages = packageManager.currentToCanonicalPackageNames(
1530 new String[] { packageName });
1531 cn = new ComponentName(packages[0], className);
1532 try {
1533 packageManager.getReceiverInfo(cn, 0);
1534 } catch (Exception e1) {
1535 hasPackage = false;
1536 }
1537 }
1538
1539 if (hasPackage) {
1540 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1541 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001542
1543 // Read the extras
1544 Bundle extras = new Bundle();
1545 int widgetDepth = parser.getDepth();
1546 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1547 parser.getDepth() > widgetDepth) {
1548 if (type != XmlPullParser.START_TAG) {
1549 continue;
1550 }
1551
1552 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1553 if (TAG_EXTRA.equals(parser.getName())) {
1554 String key = ar.getString(R.styleable.Extra_key);
1555 String value = ar.getString(R.styleable.Extra_value);
1556 if (key != null && value != null) {
1557 extras.putString(key, value);
1558 } else {
1559 throw new RuntimeException("Widget extras must have a key and value");
1560 }
1561 } else {
1562 throw new RuntimeException("Widgets can contain only extras");
1563 }
1564 ar.recycle();
1565 }
1566
1567 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001568 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001569
Romain Guy693599f2010-03-23 10:58:18 -07001570 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001571 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001572 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001573 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001574 boolean allocatedAppWidgets = false;
1575 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1576
1577 try {
1578 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001579
Mike Cleronb87bd162009-10-30 16:36:56 -07001580 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001581 values.put(Favorites.SPANX, spanX);
1582 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001583 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001584 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001585 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001586 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001587
1588 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001589
Michael Jurka8b805b12012-04-18 14:23:14 -07001590 // TODO: need to check return value
1591 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001592
1593 // Send a broadcast to configure the widget
1594 if (extras != null && !extras.isEmpty()) {
1595 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1596 intent.setComponent(cn);
1597 intent.putExtras(extras);
1598 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1599 mContext.sendBroadcast(intent);
1600 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001601 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001602 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001603 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001604
Mike Cleronb87bd162009-10-30 16:36:56 -07001605 return allocatedAppWidgets;
1606 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001607
1608 private long addUriShortcut(SQLiteDatabase db, ContentValues values,
Mike Cleronb87bd162009-10-30 16:36:56 -07001609 TypedArray a) {
1610 Resources r = mContext.getResources();
1611
1612 final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
1613 final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
1614
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001615 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001616 String uri = null;
1617 try {
1618 uri = a.getString(R.styleable.Favorite_uri);
1619 intent = Intent.parseUri(uri, 0);
1620 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001621 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001622 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001623 }
1624
1625 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001626 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001627 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001628 }
1629
Adam Cohendcd297f2013-06-18 13:13:40 -07001630 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001631 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1632 values.put(Favorites.INTENT, intent.toUri(0));
1633 values.put(Favorites.TITLE, r.getString(titleResId));
1634 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1635 values.put(Favorites.SPANX, 1);
1636 values.put(Favorites.SPANY, 1);
1637 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
1638 values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
1639 values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001640 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001641
Adam Cohen228da5a2011-07-27 22:23:47 -07001642 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1643 return -1;
1644 }
1645 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001646 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001647
1648 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1649 final ContentResolver resolver = mContext.getContentResolver();
1650 Cursor c = null;
1651 int count = 0;
1652 int curScreen = 0;
1653
1654 try {
1655 c = resolver.query(uri, null, null, null, "title ASC");
1656 } catch (Exception e) {
1657 // Ignore
1658 }
1659
Dan Sandlerd5024042014-01-09 15:01:33 -05001660 // We already have a favorites database in the old provider
1661 if (c != null) {
1662 try {
1663 if (c.getCount() > 0) {
1664 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1665 final int intentIndex
1666 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1667 final int titleIndex
1668 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1669 final int iconTypeIndex
1670 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1671 final int iconIndex
1672 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1673 final int iconPackageIndex
1674 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1675 final int iconResourceIndex
1676 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1677 final int containerIndex
1678 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1679 final int itemTypeIndex
1680 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1681 final int screenIndex
1682 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1683 final int cellXIndex
1684 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1685 final int cellYIndex
1686 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1687 final int uriIndex
1688 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1689 final int displayModeIndex
1690 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
1691
1692 int i = 0;
1693 int curX = 0;
1694 int curY = 0;
1695
1696 final LauncherAppState app = LauncherAppState.getInstance();
1697 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1698 final int width = (int) grid.numColumns;
1699 final int height = (int) grid.numRows;
1700 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001701 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001702
1703 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1704
Adam Cohen72960972014-01-15 18:13:55 -08001705 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1706 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001707 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001708
1709 while (c.moveToNext()) {
1710 final int itemType = c.getInt(itemTypeIndex);
1711 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1712 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1713 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1714 continue;
1715 }
1716
1717 final int cellX = c.getInt(cellXIndex);
1718 final int cellY = c.getInt(cellYIndex);
1719 final int screen = c.getInt(screenIndex);
1720 int container = c.getInt(containerIndex);
1721 final String intentStr = c.getString(intentIndex);
1722 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001723 + c.getString(titleIndex) + "\" ("
1724 + cellX + "," + cellY + "@"
1725 + LauncherSettings.Favorites.containerToString(container)
1726 + "/" + screen
1727 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001728
1729 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001730
1731 final Intent intent;
1732 final ComponentName cn;
1733 try {
1734 intent = Intent.parseUri(intentStr, 0);
1735 } catch (URISyntaxException e) {
1736 // bogus intent?
1737 Launcher.addDumpLog(TAG,
1738 "skipping invalid intent uri", true);
1739 continue;
1740 }
1741
1742 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001743 if (TextUtils.isEmpty(intentStr)) {
1744 // no intent? no icon
1745 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1746 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001747 } else if (cn != null &&
1748 !LauncherModel.isValidPackageComponent(pm, cn)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001749 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001750 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001751 "no longer exists.", true);
1752 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001753 } else if (container ==
1754 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1755 // Dedupe icons directly on the workspace
1756
Adam Cohen556f6132014-01-15 15:18:08 -08001757 // Canonicalize
1758 // the Play Store sets the package parameter, but Launcher
1759 // does not, so we clear that out to keep them the same
1760 intent.setPackage(null);
1761 final String key = intent.toUri(0);
1762 if (seenIntents.contains(key)) {
1763 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001764 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001765 } else {
1766 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001767 }
1768 }
1769 }
1770
1771 ContentValues values = new ContentValues(c.getColumnCount());
1772 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1773 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1774 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1775 values.put(LauncherSettings.Favorites.ICON_TYPE,
1776 c.getInt(iconTypeIndex));
1777 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1778 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1779 c.getString(iconPackageIndex));
1780 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1781 c.getString(iconResourceIndex));
1782 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1783 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1784 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1785 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1786 c.getInt(displayModeIndex));
1787
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001788 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1789 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001790 }
1791
1792 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1793 // In a folder or in the hotseat, preserve position
1794 values.put(LauncherSettings.Favorites.SCREEN, screen);
1795 values.put(LauncherSettings.Favorites.CELLX, cellX);
1796 values.put(LauncherSettings.Favorites.CELLY, cellY);
1797 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001798 // For items contained directly on one of the workspace screen,
1799 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001800 }
1801
1802 values.put(LauncherSettings.Favorites.CONTAINER, container);
1803
Adam Cohen72960972014-01-15 18:13:55 -08001804 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1805 shortcuts.add(values);
1806 } else {
1807 folders.add(values);
1808 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001809 }
1810
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001811 // Now that we have all the hotseat icons, let's go through them left-right
1812 // and assign valid locations for them in the new hotseat
1813 final int N = hotseat.size();
1814 for (int idx=0; idx<N; idx++) {
1815 int hotseatX = hotseat.keyAt(idx);
1816 ContentValues values = hotseat.valueAt(idx);
1817
1818 if (hotseatX == grid.hotseatAllAppsRank) {
1819 // let's drop this in the next available hole in the hotseat
1820 while (++hotseatX < hotseatWidth) {
1821 if (hotseat.get(hotseatX) == null) {
1822 // found a spot! move it here
1823 values.put(LauncherSettings.Favorites.SCREEN,
1824 hotseatX);
1825 break;
1826 }
1827 }
1828 }
1829 if (hotseatX >= hotseatWidth) {
1830 // no room for you in the hotseat? it's off to the desktop with you
1831 values.put(LauncherSettings.Favorites.CONTAINER,
1832 Favorites.CONTAINER_DESKTOP);
1833 }
1834 }
1835
Adam Cohen72960972014-01-15 18:13:55 -08001836 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1837 // Folders first
1838 allItems.addAll(folders);
1839 // Then shortcuts
1840 allItems.addAll(shortcuts);
1841
1842 // Layout all the folders
1843 for (ContentValues values: allItems) {
1844 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1845 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1846 // Hotseat items and folder items have already had their
1847 // location information set. Nothing to be done here.
1848 continue;
1849 }
1850 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1851 values.put(LauncherSettings.Favorites.CELLX, curX);
1852 values.put(LauncherSettings.Favorites.CELLY, curY);
1853 curX = (curX + 1) % width;
1854 if (curX == 0) {
1855 curY = (curY + 1);
1856 }
1857 // Leave the last row of icons blank on every screen
1858 if (curY == height - 1) {
1859 curScreen = (int) generateNewScreenId();
1860 curY = 0;
1861 }
1862 }
1863
1864 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001865 db.beginTransaction();
1866 try {
Adam Cohen72960972014-01-15 18:13:55 -08001867 for (ContentValues row: allItems) {
1868 if (row == null) continue;
1869 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001870 < 0) {
1871 return;
1872 } else {
1873 count++;
1874 }
1875 }
1876 db.setTransactionSuccessful();
1877 } finally {
1878 db.endTransaction();
1879 }
1880 }
1881
1882 db.beginTransaction();
1883 try {
1884 for (i=0; i<=curScreen; i++) {
1885 final ContentValues values = new ContentValues();
1886 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1887 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1888 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1889 < 0) {
1890 return;
1891 }
1892 }
1893 db.setTransactionSuccessful();
1894 } finally {
1895 db.endTransaction();
1896 }
1897 }
1898 } finally {
1899 c.close();
1900 }
1901 }
1902
1903 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1904 + (curScreen+1) + " screens", true);
1905
1906 // ensure that new screens are created to hold these icons
1907 setFlagJustLoadedOldDb();
1908
1909 // Update max IDs; very important since we just grabbed IDs from another database
1910 mMaxItemId = initializeMaxItemId(db);
1911 mMaxScreenId = initializeMaxScreenId(db);
1912 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1913 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001914 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001915
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001916 /**
1917 * Build a query string that will match any row where the column matches
1918 * anything in the values list.
1919 */
1920 static String buildOrWhereString(String column, int[] values) {
1921 StringBuilder selectWhere = new StringBuilder();
1922 for (int i = values.length - 1; i >= 0; i--) {
1923 selectWhere.append(column).append("=").append(values[i]);
1924 if (i > 0) {
1925 selectWhere.append(" OR ");
1926 }
1927 }
1928 return selectWhere.toString();
1929 }
1930
1931 static class SqlArguments {
1932 public final String table;
1933 public final String where;
1934 public final String[] args;
1935
1936 SqlArguments(Uri url, String where, String[] args) {
1937 if (url.getPathSegments().size() == 1) {
1938 this.table = url.getPathSegments().get(0);
1939 this.where = where;
1940 this.args = args;
1941 } else if (url.getPathSegments().size() != 2) {
1942 throw new IllegalArgumentException("Invalid URI: " + url);
1943 } else if (!TextUtils.isEmpty(where)) {
1944 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1945 } else {
1946 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001947 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001948 this.args = null;
1949 }
1950 }
1951
1952 SqlArguments(Uri url) {
1953 if (url.getPathSegments().size() == 1) {
1954 table = url.getPathSegments().get(0);
1955 where = null;
1956 args = null;
1957 } else {
1958 throw new IllegalArgumentException("Invalid URI: " + url);
1959 }
1960 }
1961 }
Adam Cohen72960972014-01-15 18:13:55 -08001962}