blob: 93708b5ed952fb00a5f07b3b79c03e8be6240f4e [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;
Jeff Sharkey5aeef582014-04-14 13:26:42 -070036import android.content.pm.PackageInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.content.pm.PackageManager;
Jason Monk41314972014-03-03 16:11:30 -050038import android.content.pm.ResolveInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.content.res.XmlResourceParser;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.database.Cursor;
43import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteOpenHelper;
46import android.database.sqlite.SQLiteQueryBuilder;
47import android.database.sqlite.SQLiteStatement;
Joe Onorato0589f0f2010-02-08 13:44:00 -080048import android.graphics.Bitmap;
49import android.graphics.BitmapFactory;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.net.Uri;
Winson Chungb3302ae2012-05-01 10:19:14 -070051import android.os.Bundle;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import android.provider.Settings;
53import android.text.TextUtils;
54import android.util.AttributeSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050056import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080057import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070058
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040061import com.android.launcher3.config.ProviderConfig;
Kenny Guyed131872014-04-30 03:02:21 +010062import com.android.launcher3.LauncherSettings.Favorites;
Michael Jurka8b805b12012-04-18 14:23:14 -070063
64import org.xmlpull.v1.XmlPullParser;
65import org.xmlpull.v1.XmlPullParserException;
66
Dan Sandlerd5024042014-01-09 15:01:33 -050067import java.io.File;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068import java.io.IOException;
Mike Cleronb87bd162009-10-30 16:36:56 -070069import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070070import java.util.ArrayList;
Dan Sandlerd5024042014-01-09 15:01:33 -050071import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000072import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080075 private static final String TAG = "Launcher.LauncherProvider";
76 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
78 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070079
Kenny Guyed131872014-04-30 03:02:21 +010080 private static final int DATABASE_VERSION = 20;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
Adam Cohene25af792013-06-06 23:08:25 -070082 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040083 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070084
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050085 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050086 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050087
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070089 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070091 static final String UPGRADED_FROM_OLD_DATABASE =
92 "UPGRADED_FROM_OLD_DATABASE";
93 static final String EMPTY_DATABASE_CREATED =
94 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020095 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
96 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
Winson Chungb3302ae2012-05-01 10:19:14 -070098 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -070099 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -0700100
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700101 private LauncherProviderChangeListener mListener;
102
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700103 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700104 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700105 * {@link AppWidgetHost#deleteHost()} is called during database creation.
106 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
107 */
108 static final Uri CONTENT_APPWIDGET_RESET_URI =
109 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700110
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700111 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700112 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
114 @Override
115 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400116 final Context context = getContext();
117 mOpenHelper = new DatabaseHelper(context);
118 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119 return true;
120 }
121
Winson Chung0b560dd2014-01-21 13:00:26 -0800122 public boolean wasNewDbCreated() {
123 return mOpenHelper.wasNewDbCreated();
124 }
125
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700126 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
127 mListener = listener;
128 }
129
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800130 @Override
131 public String getType(Uri uri) {
132 SqlArguments args = new SqlArguments(uri, null, null);
133 if (TextUtils.isEmpty(args.where)) {
134 return "vnd.android.cursor.dir/" + args.table;
135 } else {
136 return "vnd.android.cursor.item/" + args.table;
137 }
138 }
139
140 @Override
141 public Cursor query(Uri uri, String[] projection, String selection,
142 String[] selectionArgs, String sortOrder) {
143
144 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
145 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
146 qb.setTables(args.table);
147
Romain Guy73b979d2009-06-09 12:57:21 -0700148 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
150 result.setNotificationUri(getContext().getContentResolver(), uri);
151
152 return result;
153 }
154
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 private static long dbInsertAndCheck(DatabaseHelper helper,
156 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500157 if (values == null) {
158 throw new RuntimeException("Error: attempting to insert null values");
159 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500160 if (!values.containsKey(LauncherSettings.BaseLauncherColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 throw new RuntimeException("Error: attempting to add item without specifying an id");
162 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500163 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 return db.insert(table, nullColumnHack, values);
165 }
166
Adam Cohen228da5a2011-07-27 22:23:47 -0700167 private static void deleteId(SQLiteDatabase db, long id) {
168 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
169 SqlArguments args = new SqlArguments(uri, null, null);
170 db.delete(args.table, args.where, args.args);
171 }
172
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173 @Override
174 public Uri insert(Uri uri, ContentValues initialValues) {
175 SqlArguments args = new SqlArguments(uri);
176
177 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400178 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700179 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 if (rowId <= 0) return null;
181
182 uri = ContentUris.withAppendedId(uri, rowId);
183 sendNotify(uri);
184
185 return uri;
186 }
187
188 @Override
189 public int bulkInsert(Uri uri, ContentValues[] values) {
190 SqlArguments args = new SqlArguments(uri);
191
192 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
193 db.beginTransaction();
194 try {
195 int numValues = values.length;
196 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400197 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700198 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
199 return 0;
200 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 }
202 db.setTransactionSuccessful();
203 } finally {
204 db.endTransaction();
205 }
206
207 sendNotify(uri);
208 return values.length;
209 }
210
211 @Override
Yura085c8532014-02-11 15:15:29 +0000212 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
213 throws OperationApplicationException {
214 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
215 db.beginTransaction();
216 try {
217 ContentProviderResult[] result = super.applyBatch(operations);
218 db.setTransactionSuccessful();
219 return result;
220 } finally {
221 db.endTransaction();
222 }
223 }
224
225 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800226 public int delete(Uri uri, String selection, String[] selectionArgs) {
227 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
228
229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
230 int count = db.delete(args.table, args.where, args.args);
231 if (count > 0) sendNotify(uri);
232
233 return count;
234 }
235
236 @Override
237 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
238 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
239
Chris Wren1ada10d2013-09-13 18:01:38 -0400240 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
242 int count = db.update(args.table, values, args.where, args.args);
243 if (count > 0) sendNotify(uri);
244
245 return count;
246 }
247
248 private void sendNotify(Uri uri) {
249 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
250 if (notify == null || "true".equals(notify)) {
251 getContext().getContentResolver().notifyChange(uri, null);
252 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400253
254 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400255 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700256 if (mListener != null) {
257 mListener.onLauncherProviderChange();
258 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400259 }
260
261 private void addModifiedTime(ContentValues values) {
262 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800263 }
264
Adam Cohendcd297f2013-06-18 13:13:40 -0700265 public long generateNewItemId() {
266 return mOpenHelper.generateNewItemId();
267 }
268
Winson Chungc763c4e2013-07-19 13:49:06 -0700269 public void updateMaxItemId(long id) {
270 mOpenHelper.updateMaxItemId(id);
271 }
272
Adam Cohendcd297f2013-06-18 13:13:40 -0700273 public long generateNewScreenId() {
274 return mOpenHelper.generateNewScreenId();
275 }
276
277 // This is only required one time while loading the workspace during the
278 // upgrade path, and should never be called from anywhere else.
279 public void updateMaxScreenId(long maxScreenId) {
280 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700281 }
282
Brian Muramatsu5524b492012-10-02 16:55:54 -0700283 /**
Adam Cohene25af792013-06-06 23:08:25 -0700284 * @param Should we load the old db for upgrade? first run only.
285 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700286 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400287 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700288 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
289
Winson Chungc763c4e2013-07-19 13:49:06 -0700290 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700291
Winson Chungc763c4e2013-07-19 13:49:06 -0700292 sJustLoadedFromOldDb = false;
293 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700294
295 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700296 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700297 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700298 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700299 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700300 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700301 }
302
303 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700304 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
305 */
Michael Jurka45355c42012-10-08 13:21:35 +0200306 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400307 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700308 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700309
Winson Chungc763c4e2013-07-19 13:49:06 -0700310 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500311 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200312 int workspaceResId = origWorkspaceResId;
313
Brian Muramatsu5524b492012-10-02 16:55:54 -0700314 // Use default workspace resource if none provided
315 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800316 workspaceResId =
317 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700318 }
319
Michael Jurkab85f8a42012-04-25 15:48:32 -0700320 // Populate favorites table with initial favorites
321 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700322 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200323 if (origWorkspaceResId != 0) {
324 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
325 }
Adam Cohene25af792013-06-06 23:08:25 -0700326
Brian Muramatsu5524b492012-10-02 16:55:54 -0700327 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700328 mOpenHelper.setFlagJustLoadedOldDb();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700329 editor.commit();
330 }
331 }
332
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 public void migrateLauncher2Shortcuts() {
334 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400335 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 }
337
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800338 private static int getDefaultWorkspaceResourceId() {
Winson Chungbe876472014-05-14 14:15:20 -0700339 LauncherAppState app = LauncherAppState.getInstance();
340 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800341 if (LauncherAppState.isDisableAllApps()) {
Winson Chungbe876472014-05-14 14:15:20 -0700342 return grid.defaultNoAllAppsLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800343 } else {
Winson Chungbe876472014-05-14 14:15:20 -0700344 return grid.defaultLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800345 }
346 }
347
Winson Chungc763c4e2013-07-19 13:49:06 -0700348 private static interface ContentValuesCallback {
349 public void onRow(ContentValues values);
350 }
351
Adam Cohen6dbe0492013-12-02 17:00:14 -0800352 private static boolean shouldImportLauncher2Database(Context context) {
353 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
354
355 // We don't import the old databse for tablets, as the grid size has changed.
356 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
357 }
358
Dan Sandlerd5024042014-01-09 15:01:33 -0500359 public void deleteDatabase() {
360 // Are you sure? (y/n)
361 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500362 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500363 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500364 if (dbFile.exists()) {
365 SQLiteDatabase.deleteDatabase(dbFile);
366 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500367 mOpenHelper = new DatabaseHelper(getContext());
368 }
369
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800370 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500371 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800372 private static final String TAG_FAVORITES = "favorites";
373 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700374 private static final String TAG_CLOCK = "clock";
375 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700376 private static final String TAG_APPWIDGET = "appwidget";
377 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700378 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700379 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700380 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400381 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700382
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700383 private static final String ATTR_TITLE = "title";
384 private static final String ATTR_ICON = "icon";
385 private static final String ATTR_URI = "uri";
386 private static final String ATTR_PACKAGE_NAME = "packageName";
387 private static final String ATTR_CLASS_NAME = "className";
388
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700390 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700391 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700392 private long mMaxItemId = -1;
393 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394
Winson Chung0b560dd2014-01-21 13:00:26 -0800395 private boolean mNewDbCreated = false;
396
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 DatabaseHelper(Context context) {
398 super(context, DATABASE_NAME, null, DATABASE_VERSION);
399 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700400 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700401 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700402
403 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
404 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700405 if (mMaxItemId == -1) {
406 mMaxItemId = initializeMaxItemId(getWritableDatabase());
407 }
408 if (mMaxScreenId == -1) {
409 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700410 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800411 }
412
Winson Chung0b560dd2014-01-21 13:00:26 -0800413 public boolean wasNewDbCreated() {
414 return mNewDbCreated;
415 }
416
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700417 /**
418 * Send notification that we've deleted the {@link AppWidgetHost},
419 * probably as part of the initial database creation. The receiver may
420 * want to re-call {@link AppWidgetHost#startListening()} to ensure
421 * callbacks are correctly set.
422 */
423 private void sendAppWidgetResetNotify() {
424 final ContentResolver resolver = mContext.getContentResolver();
425 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
426 }
427
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800428 @Override
429 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800430 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700431
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 mMaxItemId = 1;
433 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800434 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700435
Kenny Guyed131872014-04-30 03:02:21 +0100436 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
437 long userSerialNumber = userManager.getSerialNumberForUser(
438 UserHandleCompat.myUserHandle());
439
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800440 db.execSQL("CREATE TABLE favorites (" +
441 "_id INTEGER PRIMARY KEY," +
442 "title TEXT," +
443 "intent TEXT," +
444 "container INTEGER," +
445 "screen INTEGER," +
446 "cellX INTEGER," +
447 "cellY INTEGER," +
448 "spanX INTEGER," +
449 "spanY INTEGER," +
450 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700451 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800452 "isShortcut INTEGER," +
453 "iconType INTEGER," +
454 "iconPackage TEXT," +
455 "iconResource TEXT," +
456 "icon BLOB," +
457 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400458 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400459 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500460 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100461 "restored INTEGER NOT NULL DEFAULT 0," +
462 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700464 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700466 // Database was just created, so wipe any previous widgets
467 if (mAppWidgetHost != null) {
468 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700469 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800470 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700471
Adam Cohen6dbe0492013-12-02 17:00:14 -0800472 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500473 // Try converting the old database
474 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
475 public void onRow(ContentValues values) {
476 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
477 if (container == Favorites.CONTAINER_DESKTOP) {
478 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
479 screen = (int) upgradeLauncherDb_permuteScreens(screen);
480 values.put(LauncherSettings.Favorites.SCREEN, screen);
481 }
482 }
483 };
484 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
485 "/old_favorites?notify=true");
486 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
487 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400488 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500489 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
490 // If we fail, then set a flag to load the default workspace
491 setFlagEmptyDbCreated();
492 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700493 }
494 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500495 // Right now, in non-default workspace cases, we want to run the final
496 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
497 // set that flag too.
498 setFlagJustLoadedOldDb();
499 } else {
500 // Fresh and clean launcher DB.
501 mMaxItemId = initializeMaxItemId(db);
502 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800503 }
504 }
505
Adam Cohendcd297f2013-06-18 13:13:40 -0700506 private void addWorkspacesTable(SQLiteDatabase db) {
507 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
508 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400509 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
510 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700511 ");");
512 }
513
Adam Cohen119285e2014-04-02 16:59:08 -0700514 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700515 // Delete items directly on the workspace who's screen id doesn't exist
516 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
517 // AND container = -100"
518 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
519 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700520 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700521 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
522 " AND " +
523 LauncherSettings.Favorites.CONTAINER + " = " +
524 LauncherSettings.Favorites.CONTAINER_DESKTOP;
525 db.execSQL(removeOrphanedDesktopItems);
526
527 // Delete items contained in folders which no longer exist (after above statement)
528 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
529 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
530 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
531 " WHERE " +
532 LauncherSettings.Favorites.CONTAINER + " <> " +
533 LauncherSettings.Favorites.CONTAINER_DESKTOP +
534 " AND "
535 + LauncherSettings.Favorites.CONTAINER + " <> " +
536 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
537 " AND "
538 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
539 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
540 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
541 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
542 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700543 }
544
Winson Chungc763c4e2013-07-19 13:49:06 -0700545 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400546 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700547 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
548 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700549 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
550 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700551 editor.commit();
552 }
553
Winson Chungc763c4e2013-07-19 13:49:06 -0700554 private void setFlagEmptyDbCreated() {
555 String spKey = LauncherAppState.getSharedPreferencesKey();
556 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
557 SharedPreferences.Editor editor = sp.edit();
558 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
559 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
560 editor.commit();
561 }
562
563 // We rearrange the screens from the old launcher
564 // 12345 -> 34512
565 private long upgradeLauncherDb_permuteScreens(long screen) {
566 if (screen >= 2) {
567 return screen - 2;
568 } else {
569 return screen + 3;
570 }
571 }
572
573 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
574 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800575 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 boolean converted = false;
577
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 final ContentResolver resolver = mContext.getContentResolver();
579 Cursor cursor = null;
580
581 try {
582 cursor = resolver.query(uri, null, null, null, null);
583 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700584 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 }
586
587 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700588 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700590 if (cursor.getCount() > 0) {
591 converted = copyFromCursor(db, cursor, cb) > 0;
592 if (converted && deleteRows) {
593 resolver.delete(uri, null, null);
594 }
595 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 } finally {
597 cursor.close();
598 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700600
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700602 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800603 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800604 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700605
606 // Update max item id
607 mMaxItemId = initializeMaxItemId(db);
608 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609 }
610
611 return converted;
612 }
613
Winson Chungc763c4e2013-07-19 13:49:06 -0700614 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700615 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
617 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
618 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
619 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
620 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
621 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
622 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
623 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
624 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
625 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
626 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
627 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
628 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
629
630 ContentValues[] rows = new ContentValues[c.getCount()];
631 int i = 0;
632 while (c.moveToNext()) {
633 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700634 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
636 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
637 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
638 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
639 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
640 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
641 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
642 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700643 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800644 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
645 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
646 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
647 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
648 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700649 if (cb != null) {
650 cb.onRow(values);
651 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652 rows[i++] = values;
653 }
654
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800655 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700656 if (i > 0) {
657 db.beginTransaction();
658 try {
659 int numValues = rows.length;
660 for (i = 0; i < numValues; i++) {
661 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
662 return 0;
663 } else {
664 total++;
665 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800666 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700667 db.setTransactionSuccessful();
668 } finally {
669 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800671 }
672
673 return total;
674 }
675
676 @Override
677 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700678 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700679
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800680 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700681 if (version < 3) {
682 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800683 db.beginTransaction();
684 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700685 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700687 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700689 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800690 } catch (SQLException ex) {
691 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800692 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800693 } finally {
694 db.endTransaction();
695 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700696
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700698 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 convertWidgets(db);
700 }
701 }
Romain Guy73b979d2009-06-09 12:57:21 -0700702
703 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800704 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700705 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700706
Romain Guy509cd6a2010-03-23 15:10:56 -0700707 // Where's version 5?
708 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400709 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700710 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
711 // but version 5 on there was the updateContactsShortcuts change
712 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
713 // The updateContactsShortcuts change is idempotent, so running it twice
714 // is okay so we'll do that when upgrading the devices that shipped with it.
715 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800716 // We went from 3 to 5 screens. Move everything 1 to the right
717 db.beginTransaction();
718 try {
719 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
720 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800721 } catch (SQLException ex) {
722 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800723 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800724 } finally {
725 db.endTransaction();
726 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700727
Romain Guy509cd6a2010-03-23 15:10:56 -0700728 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800729 if (updateContactsShortcuts(db)) {
730 version = 6;
731 }
732 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000733
734 if (version < 7) {
735 // Version 7 gets rid of the special search widget.
736 convertWidgets(db);
737 version = 7;
738 }
739
Joe Onorato0589f0f2010-02-08 13:44:00 -0800740 if (version < 8) {
741 // Version 8 (froyo) has the icons all normalized. This should
742 // already be the case in practice, but we now rely on it and don't
743 // resample the images each time.
744 normalizeIcons(db);
745 version = 8;
746 }
747
Winson Chung3d503fb2011-07-13 17:25:49 -0700748 if (version < 9) {
749 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
750 // 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 -0700751 if (mMaxItemId == -1) {
752 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700753 }
754
755 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800756 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700757 version = 9;
758 }
759
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700760 // We bumped the version three time during JB, once to update the launch flags, once to
761 // update the override for the default launch animation and once to set the mimetype
762 // to improve startup performance
763 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700764 // Contact shortcuts need a different set of flags to be launched now
765 // The updateContactsShortcuts change is idempotent, so we can keep using it like
766 // back in the Donut days
767 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700768 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700769 }
770
Adam Cohendcd297f2013-06-18 13:13:40 -0700771 if (version < 13) {
772 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
773 // to persist workspace screens and their relative order.
774 mMaxScreenId = 0;
775
776 // This will never happen in the wild, but when we switch to using workspace
777 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700778 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700779
780 addWorkspacesTable(db);
781 version = 13;
782 }
783
Chris Wrend5e66bf2013-09-16 14:02:29 -0400784 if (version < 14) {
785 db.beginTransaction();
786 try {
787 // Insert new column for holding widget provider name
788 db.execSQL("ALTER TABLE favorites " +
789 "ADD COLUMN appWidgetProvider TEXT;");
790 db.setTransactionSuccessful();
791 version = 14;
792 } catch (SQLException ex) {
793 // Old version remains, which means we wipe old data
794 Log.e(TAG, ex.getMessage(), ex);
795 } finally {
796 db.endTransaction();
797 }
798 }
799
Chris Wren1ada10d2013-09-13 18:01:38 -0400800 if (version < 15) {
801 db.beginTransaction();
802 try {
803 // Insert new column for holding update timestamp
804 db.execSQL("ALTER TABLE favorites " +
805 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
806 db.execSQL("ALTER TABLE workspaceScreens " +
807 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
808 db.setTransactionSuccessful();
809 version = 15;
810 } catch (SQLException ex) {
811 // Old version remains, which means we wipe old data
812 Log.e(TAG, ex.getMessage(), ex);
813 } finally {
814 db.endTransaction();
815 }
816 }
817
Chris Wrenf4d08112014-01-16 18:13:56 -0500818
819 if (version < 16) {
820 db.beginTransaction();
821 try {
822 // Insert new column for holding restore status
823 db.execSQL("ALTER TABLE favorites " +
824 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
825 db.setTransactionSuccessful();
826 version = 16;
827 } catch (SQLException ex) {
828 // Old version remains, which means we wipe old data
829 Log.e(TAG, ex.getMessage(), ex);
830 } finally {
831 db.endTransaction();
832 }
833 }
834
Adam Cohen71e03b92014-02-21 14:09:53 -0800835 if (version < 17) {
836 // We use the db version upgrade here to identify users who may not have seen
837 // clings yet (because they weren't available), but for whom the clings are now
838 // available (tablet users). Because one of the possible cling flows (migration)
839 // is very destructive (wipes out workspaces), we want to prevent this from showing
840 // until clear data. We do so by marking that the clings have been shown.
841 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
842 version = 17;
843 }
844
Adam Cohen119285e2014-04-02 16:59:08 -0700845 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700846 // No-op
847 version = 18;
848 }
849
850 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700851 // Due to a data loss bug, some users may have items associated with screen ids
852 // which no longer exist. Since this can cause other problems, and since the user
853 // will never see these items anyway, we use database upgrade as an opportunity to
854 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700855 removeOrphanedItems(db);
856 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700857 }
858
Kenny Guyed131872014-04-30 03:02:21 +0100859 if (version < 20) {
860 // Add userId column
861 if (addProfileColumn(db)) {
862 version = 20;
863 }
864 // else old version remains, which means we wipe old data
865 }
866
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800868 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800869 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700870 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
871
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872 onCreate(db);
873 }
874 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800875
Kenny Guyed131872014-04-30 03:02:21 +0100876 private boolean addProfileColumn(SQLiteDatabase db) {
877 db.beginTransaction();
878 try {
879 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
880 // Default to the serial number of this user, for older
881 // shortcuts.
882 long userSerialNumber = userManager.getSerialNumberForUser(
883 UserHandleCompat.myUserHandle());
884 // Insert new column for holding user serial number
885 db.execSQL("ALTER TABLE favorites " +
886 "ADD COLUMN profileId INTEGER DEFAULT "
887 + userSerialNumber + ";");
888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
890 // Old version remains, which means we wipe old data
891 Log.e(TAG, ex.getMessage(), ex);
892 return false;
893 } finally {
894 db.endTransaction();
895 }
896 return true;
897 }
898
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800899 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800900 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
901 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
902
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700903 Cursor c = null;
904 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800905 db.beginTransaction();
906 try {
907 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700908 c = db.query(TABLE_FAVORITES,
909 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800910 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700911 if (c == null) return false;
912
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800913 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700914
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800915 final int idIndex = c.getColumnIndex(Favorites._ID);
916 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700917
918 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800919 long favoriteId = c.getLong(idIndex);
920 final String intentUri = c.getString(intentIndex);
921 if (intentUri != null) {
922 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700923 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800924 android.util.Log.d("Home", intent.toString());
925 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700926 if (uri != null) {
927 final String data = uri.toString();
928 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
929 actionQuickContact.equals(intent.getAction())) &&
930 (data.startsWith("content://contacts/people/") ||
931 data.startsWith("content://com.android.contacts/" +
932 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800933
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700934 final Intent newIntent = new Intent(actionQuickContact);
935 // When starting from the launcher, start in a new, cleared task
936 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
937 // clear the whole thing preemptively here since
938 // QuickContactActivity will finish itself when launching other
939 // detail activities.
940 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
941 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700942 newIntent.putExtra(
943 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700944 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700945 // Determine the type and also put that in the shortcut
946 // (that can speed up launch a bit)
947 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800948
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700949 final ContentValues values = new ContentValues();
950 values.put(LauncherSettings.Favorites.INTENT,
951 newIntent.toUri(0));
952
953 String updateWhere = Favorites._ID + "=" + favoriteId;
954 db.update(TABLE_FAVORITES, values, updateWhere, null);
955 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800956 }
957 } catch (RuntimeException ex) {
958 Log.e(TAG, "Problem upgrading shortcut", ex);
959 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700960 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800961 }
962 }
963 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700964
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800965 db.setTransactionSuccessful();
966 } catch (SQLException ex) {
967 Log.w(TAG, "Problem while upgrading contacts", ex);
968 return false;
969 } finally {
970 db.endTransaction();
971 if (c != null) {
972 c.close();
973 }
974 }
975
976 return true;
977 }
978
Joe Onorato0589f0f2010-02-08 13:44:00 -0800979 private void normalizeIcons(SQLiteDatabase db) {
980 Log.d(TAG, "normalizing icons");
981
Joe Onorato346e1292010-02-18 10:34:24 -0500982 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800983 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400984 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800985 try {
986 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400987 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600988 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800989
990 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
991 Favorites.ICON_TYPE_BITMAP, null);
992
993 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
994 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
995
996 while (c.moveToNext()) {
997 long id = c.getLong(idIndex);
998 byte[] data = c.getBlob(iconIndex);
999 try {
1000 Bitmap bitmap = Utilities.resampleIconBitmap(
1001 BitmapFactory.decodeByteArray(data, 0, data.length),
1002 mContext);
1003 if (bitmap != null) {
1004 update.bindLong(1, id);
1005 data = ItemInfo.flattenBitmap(bitmap);
1006 if (data != null) {
1007 update.bindBlob(2, data);
1008 update.execute();
1009 }
1010 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001011 }
1012 } catch (Exception e) {
1013 if (!logged) {
1014 Log.e(TAG, "Failed normalizing icon " + id, e);
1015 } else {
1016 Log.e(TAG, "Also failed normalizing icon " + id);
1017 }
1018 logged = true;
1019 }
1020 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001021 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001022 } catch (SQLException ex) {
1023 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1024 } finally {
1025 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001026 if (update != null) {
1027 update.close();
1028 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001029 if (c != null) {
1030 c.close();
1031 }
1032 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001033 }
1034
1035 // Generates a new ID to use for an object in your database. This method should be only
1036 // called from the main UI thread. As an exception, we do call it when we call the
1037 // constructor from the worker thread; however, this doesn't extend until after the
1038 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1039 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001040 public long generateNewItemId() {
1041 if (mMaxItemId < 0) {
1042 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001043 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001044 mMaxItemId += 1;
1045 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001046 }
1047
Winson Chungc763c4e2013-07-19 13:49:06 -07001048 public void updateMaxItemId(long id) {
1049 mMaxItemId = id + 1;
1050 }
1051
Chris Wren5dee7af2013-12-20 17:22:11 -05001052 public void checkId(String table, ContentValues values) {
1053 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1054 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1055 mMaxScreenId = Math.max(id, mMaxScreenId);
1056 } else {
1057 mMaxItemId = Math.max(id, mMaxItemId);
1058 }
1059 }
1060
Adam Cohendcd297f2013-06-18 13:13:40 -07001061 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001062 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1063
1064 // get the result
1065 final int maxIdIndex = 0;
1066 long id = -1;
1067 if (c != null && c.moveToNext()) {
1068 id = c.getLong(maxIdIndex);
1069 }
Michael Jurka5130e402011-10-13 04:55:35 -07001070 if (c != null) {
1071 c.close();
1072 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001073
1074 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 throw new RuntimeException("Error: could not query max item id");
1076 }
1077
1078 return id;
1079 }
1080
1081 // Generates a new ID to use for an workspace screen in your database. This method
1082 // should be only called from the main UI thread. As an exception, we do call it when we
1083 // call the constructor from the worker thread; however, this doesn't extend until after the
1084 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1085 // after that point
1086 public long generateNewScreenId() {
1087 if (mMaxScreenId < 0) {
1088 throw new RuntimeException("Error: max screen id was not initialized");
1089 }
1090 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001091 // Log to disk
1092 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001093 return mMaxScreenId;
1094 }
1095
1096 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001097 // Log to disk
1098 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001099 mMaxScreenId = maxScreenId;
1100 }
1101
1102 private long initializeMaxScreenId(SQLiteDatabase db) {
1103 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1104
1105 // get the result
1106 final int maxIdIndex = 0;
1107 long id = -1;
1108 if (c != null && c.moveToNext()) {
1109 id = c.getLong(maxIdIndex);
1110 }
1111 if (c != null) {
1112 c.close();
1113 }
1114
1115 if (id == -1) {
1116 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001117 }
1118
Winson Chunga90303b2013-11-15 13:05:06 -08001119 // Log to disk
1120 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001121 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001122 }
1123
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001124 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001125 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001126 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001127 */
1128 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001129 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001130 final int[] bindSources = new int[] {
1131 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1132 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001133 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001135
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001139
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001140 db.beginTransaction();
1141 try {
1142 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001143 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001144 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001145
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001146 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001147
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 final ContentValues values = new ContentValues();
1149 while (c != null && c.moveToNext()) {
1150 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001151 int favoriteType = c.getInt(1);
1152
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001153 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001155 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001156
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001157 if (LOGD) {
1158 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1159 + " for favoriteId=" + favoriteId);
1160 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001161 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001162 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1163 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1164
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001165 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001166 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1167 values.put(LauncherSettings.Favorites.SPANX, 4);
1168 values.put(LauncherSettings.Favorites.SPANY, 1);
1169 } else {
1170 values.put(LauncherSettings.Favorites.SPANX, 2);
1171 values.put(LauncherSettings.Favorites.SPANY, 2);
1172 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001173
1174 String updateWhere = Favorites._ID + "=" + favoriteId;
1175 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001176
Bjorn Bringert34251342009-12-15 13:33:11 +00001177 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001178 // TODO: check return value
1179 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001180 new ComponentName("com.android.alarmclock",
1181 "com.android.alarmclock.AnalogAppWidgetProvider"));
1182 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001183 // TODO: check return value
1184 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001185 new ComponentName("com.android.camera",
1186 "com.android.camera.PhotoAppWidgetProvider"));
1187 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001188 // TODO: check return value
1189 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001190 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001191 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001192 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001193 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001194 }
1195 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001196
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001197 db.setTransactionSuccessful();
1198 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001199 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001200 } finally {
1201 db.endTransaction();
1202 if (c != null) {
1203 c.close();
1204 }
1205 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001206
1207 // Update max item id
1208 mMaxItemId = initializeMaxItemId(db);
1209 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001210 }
1211
Michael Jurka8b805b12012-04-18 14:23:14 -07001212 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1213 throws XmlPullParserException, IOException {
1214 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001215 while ((type = parser.next()) != XmlPullParser.START_TAG
1216 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001217 ;
1218 }
1219
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001220 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001221 throw new XmlPullParserException("No start tag found");
1222 }
1223
1224 if (!parser.getName().equals(firstElementName)) {
1225 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1226 ", expected " + firstElementName);
1227 }
1228 }
1229
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001230 private static Intent buildMainIntent() {
1231 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1232 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1233 return intent;
1234 }
1235
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001236 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001237 * Loads the default set of favorite packages from an xml file.
1238 *
1239 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001240 * @param filterContainerId The specific container id of items to load
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001241 */
Winson Chung6d092682011-11-16 18:43:26 -08001242 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001243 ContentValues values = new ContentValues();
1244
Daniel Sandler57dac262013-10-03 13:28:36 -04001245 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1246
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001247 int i = 0;
1248 try {
Winson Chung6d092682011-11-16 18:43:26 -08001249 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001250 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001251 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001252
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001253 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001254
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001255 int type;
1256 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1257 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1258
1259 if (type != XmlPullParser.START_TAG) {
1260 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001261 }
1262
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001263 boolean added = false;
1264 final String name = parser.getName();
1265
Daniel Sandler57dac262013-10-03 13:28:36 -04001266 if (TAG_INCLUDE.equals(name)) {
1267 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1268
1269 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1270
1271 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1272 "", resId));
1273
1274 if (resId != 0 && resId != workspaceResourceId) {
1275 // recursively load some more favorites, why not?
1276 i += loadFavorites(db, resId);
1277 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001278 } else {
1279 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1280 }
1281
1282 a.recycle();
1283
1284 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1285 continue;
1286 }
1287
1288 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001289 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1290
Winson Chung3d503fb2011-07-13 17:25:49 -07001291 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1292 if (a.hasValue(R.styleable.Favorite_container)) {
1293 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1294 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001295
Winson Chung6d092682011-11-16 18:43:26 -08001296 String screen = a.getString(R.styleable.Favorite_screen);
1297 String x = a.getString(R.styleable.Favorite_x);
1298 String y = a.getString(R.styleable.Favorite_y);
1299
Winson Chung6d092682011-11-16 18:43:26 -08001300 values.clear();
1301 values.put(LauncherSettings.Favorites.CONTAINER, container);
1302 values.put(LauncherSettings.Favorites.SCREEN, screen);
1303 values.put(LauncherSettings.Favorites.CELLX, x);
1304 values.put(LauncherSettings.Favorites.CELLY, y);
1305
Daniel Sandler57dac262013-10-03 13:28:36 -04001306 if (LOGD) {
1307 final String title = a.getString(R.styleable.Favorite_title);
1308 final String pkg = a.getString(R.styleable.Favorite_packageName);
1309 final String something = title != null ? title : pkg;
1310 Log.v(TAG, String.format(
1311 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1312 "", name,
1313 (something == null ? "" : (" \"" + something + "\"")),
1314 container, screen, x, y));
1315 }
1316
Winson Chung6d092682011-11-16 18:43:26 -08001317 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001318 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001319 added = id >= 0;
1320 } else if (TAG_SEARCH.equals(name)) {
1321 added = addSearchWidget(db, values);
1322 } else if (TAG_CLOCK.equals(name)) {
1323 added = addClockWidget(db, values);
1324 } else if (TAG_APPWIDGET.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001325 added = addAppWidget(parser, attrs, type, db, values, a);
Winson Chung6d092682011-11-16 18:43:26 -08001326 } else if (TAG_SHORTCUT.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001327 long id = addUriShortcut(db, values, mContext.getResources(), parser);
Winson Chung6d092682011-11-16 18:43:26 -08001328 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001329 } else if (TAG_RESOLVE.equals(name)) {
1330 // This looks through the contained favorites (or meta-favorites) and
1331 // attempts to add them as shortcuts in the fallback group's location
1332 // until one is added successfully.
1333 added = false;
1334 final int groupDepth = parser.getDepth();
1335 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1336 parser.getDepth() > groupDepth) {
1337 if (type != XmlPullParser.START_TAG) {
1338 continue;
1339 }
1340 final String fallback_item_name = parser.getName();
1341 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1342 R.styleable.Favorite);
1343 if (!added) {
1344 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001345 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001346 added = id >= 0;
1347 } else {
1348 Log.e(TAG, "Fallback groups can contain only favorites "
1349 + ar.toString());
1350 }
1351 }
1352 ar.recycle();
1353 }
Winson Chung6d092682011-11-16 18:43:26 -08001354 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001355 // Folder contents are nested in this XML file
1356 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001357
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001358 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1359 // Folder contents come from an external XML resource
1360 final Partner partner = Partner.get(mPackageManager);
1361 if (partner != null) {
1362 final Resources partnerRes = partner.getResources();
1363 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1364 "xml", partner.getPackageName());
1365 if (resId != 0) {
1366 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1367 beginDocument(partnerParser, TAG_FOLDER);
1368 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001369 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001370 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001371 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001372 if (added) i++;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001373 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001374 }
1375 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001376 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001377 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001378 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001379 } catch (RuntimeException e) {
1380 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001381 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001382
Winson Chungc763c4e2013-07-19 13:49:06 -07001383 // Update the max item id after we have loaded the database
1384 if (mMaxItemId == -1) {
1385 mMaxItemId = initializeMaxItemId(db);
1386 }
1387
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001388 return i;
1389 }
1390
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001391 /**
1392 * Parse folder starting at current {@link XmlPullParser} location.
1393 */
1394 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1395 XmlResourceParser parser) throws IOException, XmlPullParserException {
1396 final String title;
1397 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1398 if (titleResId != 0) {
1399 title = res.getString(titleResId);
1400 } else {
1401 title = mContext.getResources().getString(R.string.folder_name);
1402 }
1403
1404 values.put(LauncherSettings.Favorites.TITLE, title);
1405 long folderId = addFolder(db, values);
1406 boolean added = folderId >= 0;
1407
1408 ArrayList<Long> folderItems = new ArrayList<Long>();
1409
1410 int type;
1411 int folderDepth = parser.getDepth();
1412 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1413 parser.getDepth() > folderDepth) {
1414 if (type != XmlPullParser.START_TAG) {
1415 continue;
1416 }
1417 final String tag = parser.getName();
1418
1419 final ContentValues childValues = new ContentValues();
1420 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1421
1422 if (LOGD) {
1423 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1424 final String uri = getAttributeValue(parser, ATTR_URI);
1425 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1426 tag, uri != null ? uri : pkg));
1427 }
1428
1429 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1430 final long id = addAppShortcut(db, childValues, parser);
1431 if (id >= 0) {
1432 folderItems.add(id);
1433 }
1434 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1435 final long id = addUriShortcut(db, childValues, res, parser);
1436 if (id >= 0) {
1437 folderItems.add(id);
1438 }
1439 } else {
1440 throw new RuntimeException("Folders can contain only shortcuts");
1441 }
1442 }
1443
1444 // We can only have folders with >= 2 items, so we need to remove the
1445 // folder and clean up if less than 2 items were included, or some
1446 // failed to add, and less than 2 were actually added
1447 if (folderItems.size() < 2 && folderId >= 0) {
1448 // Delete the folder
1449 deleteId(db, folderId);
1450
1451 // If we have a single item, promote it to where the folder
1452 // would have been.
1453 if (folderItems.size() == 1) {
1454 final ContentValues childValues = new ContentValues();
1455 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1456 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1457 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1458 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1459
1460 final long id = folderItems.get(0);
1461 db.update(TABLE_FAVORITES, childValues,
1462 LauncherSettings.Favorites._ID + "=" + id, null);
1463 } else {
1464 added = false;
1465 }
1466 }
1467 return added;
1468 }
1469
Jason Monk41314972014-03-03 16:11:30 -05001470 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1471 // logical choice for what shortcut should be used for that intent exists, then it is
1472 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001473 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1474 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001475 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001476 try {
Jason Monk41314972014-03-03 16:11:30 -05001477 metaIntent = Intent.parseUri(intentUri, 0);
1478 } catch (URISyntaxException e) {
1479 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1480 return -1;
1481 }
1482
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001483 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001484 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001485 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001486 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1487
1488 // Verify that the result is an app and not just the resolver dialog asking which
1489 // app to use.
1490 if (wouldLaunchResolverActivity(resolved, appList)) {
1491 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001492 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001493 if (systemApp == null) {
1494 // There is no logical choice for this meta-favorite, so rather than making
1495 // a bad choice just add nothing.
1496 Log.w(TAG, "No preference or single system activity found for "
1497 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001498 return -1;
1499 }
Jason Monk41314972014-03-03 16:11:30 -05001500 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001501 }
Jason Monk41314972014-03-03 16:11:30 -05001502 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001503 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001504 intent.setComponent(new ComponentName(info.packageName, info.name));
1505 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1506 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1507
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001508 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001509 }
1510
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001511 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001512 ResolveInfo systemResolve = null;
1513 final int N = appList.size();
1514 for (int i = 0; i < N; ++i) {
1515 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001516 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001517 appList.get(i).activityInfo.packageName, 0);
1518 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1519 if (systemResolve != null) {
1520 return null;
1521 } else {
1522 systemResolve = appList.get(i);
1523 }
1524 }
1525 } catch (PackageManager.NameNotFoundException e) {
1526 Log.w(TAG, "Unable to get info about resolve results", e);
1527 return null;
1528 }
1529 }
1530 return systemResolve;
1531 }
1532
1533 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1534 List<ResolveInfo> appList) {
1535 // If the list contains the above resolved activity, then it can't be
1536 // ResolverActivity itself.
1537 for (int i = 0; i < appList.size(); ++i) {
1538 ResolveInfo tmp = appList.get(i);
1539 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1540 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1541 return false;
1542 }
1543 }
1544 return true;
1545 }
1546
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001547 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1548 XmlResourceParser parser) {
1549 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1550 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1551 final String uri = getAttributeValue(parser, ATTR_URI);
1552
1553 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001554 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001555 try {
1556 ComponentName cn;
1557 try {
1558 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001559 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001560 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001561 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001562 new String[] { packageName });
1563 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001564 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001565 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001566 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001567 intent.setComponent(cn);
1568 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1569 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1570
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001571 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001572 intent);
1573 } catch (PackageManager.NameNotFoundException e) {
1574 Log.w(TAG, "Unable to add favorite: " + packageName +
1575 "/" + className, e);
1576 }
1577 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001578 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001579 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001580 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001581 } else {
1582 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1583 return -1;
1584 }
1585 }
1586
1587 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1588 Intent intent) {
1589 long id = generateNewItemId();
1590 values.put(Favorites.INTENT, intent.toUri(0));
1591 values.put(Favorites.TITLE, title);
1592 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1593 values.put(Favorites.SPANX, 1);
1594 values.put(Favorites.SPANY, 1);
1595 values.put(Favorites._ID, id);
1596 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1597 return -1;
1598 } else {
1599 return id;
1600 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001601 }
1602
1603 private long addFolder(SQLiteDatabase db, ContentValues values) {
1604 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1605 values.put(Favorites.SPANX, 1);
1606 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001607 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001608 values.put(Favorites._ID, id);
1609 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1610 return -1;
1611 } else {
1612 return id;
1613 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001614 }
1615
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001616 private ComponentName getSearchWidgetProvider() {
1617 SearchManager searchManager =
1618 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1619 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1620 if (searchComponent == null) return null;
1621 return getProviderInPackage(searchComponent.getPackageName());
1622 }
1623
1624 /**
1625 * Gets an appwidget provider from the given package. If the package contains more than
1626 * one appwidget provider, an arbitrary one is returned.
1627 */
1628 private ComponentName getProviderInPackage(String packageName) {
1629 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1630 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1631 if (providers == null) return null;
1632 final int providerCount = providers.size();
1633 for (int i = 0; i < providerCount; i++) {
1634 ComponentName provider = providers.get(i).provider;
1635 if (provider != null && provider.getPackageName().equals(packageName)) {
1636 return provider;
1637 }
1638 }
1639 return null;
1640 }
1641
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001642 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001643 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001644 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001645 }
1646
1647 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001648 ComponentName cn = new ComponentName("com.android.alarmclock",
1649 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001650 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001651 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001652
Winson Chungb3302ae2012-05-01 10:19:14 -07001653 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001654 SQLiteDatabase db, ContentValues values, TypedArray a)
1655 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001656
Mike Cleronb87bd162009-10-30 16:36:56 -07001657 String packageName = a.getString(R.styleable.Favorite_packageName);
1658 String className = a.getString(R.styleable.Favorite_className);
1659
1660 if (packageName == null || className == null) {
1661 return false;
1662 }
Romain Guy693599f2010-03-23 10:58:18 -07001663
1664 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001665 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001666 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001667 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001668 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001669 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001670 new String[] { packageName });
1671 cn = new ComponentName(packages[0], className);
1672 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001673 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001674 } catch (Exception e1) {
1675 hasPackage = false;
1676 }
1677 }
1678
1679 if (hasPackage) {
1680 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1681 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001682
1683 // Read the extras
1684 Bundle extras = new Bundle();
1685 int widgetDepth = parser.getDepth();
1686 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1687 parser.getDepth() > widgetDepth) {
1688 if (type != XmlPullParser.START_TAG) {
1689 continue;
1690 }
1691
1692 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1693 if (TAG_EXTRA.equals(parser.getName())) {
1694 String key = ar.getString(R.styleable.Extra_key);
1695 String value = ar.getString(R.styleable.Extra_value);
1696 if (key != null && value != null) {
1697 extras.putString(key, value);
1698 } else {
1699 throw new RuntimeException("Widget extras must have a key and value");
1700 }
1701 } else {
1702 throw new RuntimeException("Widgets can contain only extras");
1703 }
1704 ar.recycle();
1705 }
1706
1707 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001708 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001709
Romain Guy693599f2010-03-23 10:58:18 -07001710 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001711 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001712 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001713 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001714 boolean allocatedAppWidgets = false;
1715 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1716
1717 try {
1718 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001719
Mike Cleronb87bd162009-10-30 16:36:56 -07001720 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001721 values.put(Favorites.SPANX, spanX);
1722 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001723 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001724 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001725 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001726 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001727
1728 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001729
Michael Jurka8b805b12012-04-18 14:23:14 -07001730 // TODO: need to check return value
1731 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001732
1733 // Send a broadcast to configure the widget
1734 if (extras != null && !extras.isEmpty()) {
1735 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1736 intent.setComponent(cn);
1737 intent.putExtras(extras);
1738 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1739 mContext.sendBroadcast(intent);
1740 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001741 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001742 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001743 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001744
Mike Cleronb87bd162009-10-30 16:36:56 -07001745 return allocatedAppWidgets;
1746 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001747
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001748 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1749 XmlResourceParser parser) {
1750 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1751 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001752
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001753 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001754 String uri = null;
1755 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001756 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001757 intent = Intent.parseUri(uri, 0);
1758 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001759 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001760 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001761 }
1762
1763 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001764 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001765 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001766 }
1767
Adam Cohendcd297f2013-06-18 13:13:40 -07001768 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001769 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1770 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001771 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001772 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1773 values.put(Favorites.SPANX, 1);
1774 values.put(Favorites.SPANY, 1);
1775 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001776 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1777 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001778 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001779
Adam Cohen228da5a2011-07-27 22:23:47 -07001780 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1781 return -1;
1782 }
1783 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001784 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001785
1786 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1787 final ContentResolver resolver = mContext.getContentResolver();
1788 Cursor c = null;
1789 int count = 0;
1790 int curScreen = 0;
1791
1792 try {
1793 c = resolver.query(uri, null, null, null, "title ASC");
1794 } catch (Exception e) {
1795 // Ignore
1796 }
1797
Dan Sandlerd5024042014-01-09 15:01:33 -05001798 // We already have a favorites database in the old provider
1799 if (c != null) {
1800 try {
1801 if (c.getCount() > 0) {
1802 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1803 final int intentIndex
1804 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1805 final int titleIndex
1806 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1807 final int iconTypeIndex
1808 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1809 final int iconIndex
1810 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1811 final int iconPackageIndex
1812 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1813 final int iconResourceIndex
1814 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1815 final int containerIndex
1816 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1817 final int itemTypeIndex
1818 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1819 final int screenIndex
1820 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1821 final int cellXIndex
1822 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1823 final int cellYIndex
1824 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1825 final int uriIndex
1826 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1827 final int displayModeIndex
1828 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001829 final int profileIndex
1830 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001831
1832 int i = 0;
1833 int curX = 0;
1834 int curY = 0;
1835
1836 final LauncherAppState app = LauncherAppState.getInstance();
1837 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1838 final int width = (int) grid.numColumns;
1839 final int height = (int) grid.numRows;
1840 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001841 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001842
1843 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1844
Adam Cohen72960972014-01-15 18:13:55 -08001845 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1846 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001847 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001848
1849 while (c.moveToNext()) {
1850 final int itemType = c.getInt(itemTypeIndex);
1851 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1852 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1853 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1854 continue;
1855 }
1856
1857 final int cellX = c.getInt(cellXIndex);
1858 final int cellY = c.getInt(cellYIndex);
1859 final int screen = c.getInt(screenIndex);
1860 int container = c.getInt(containerIndex);
1861 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001862
1863 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1864 UserHandleCompat userHandle;
1865 final long userSerialNumber;
1866 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1867 userSerialNumber = c.getInt(profileIndex);
1868 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1869 } else {
1870 // Default to the serial number of this user, for older
1871 // shortcuts.
1872 userHandle = UserHandleCompat.myUserHandle();
1873 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1874 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001875 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001876 + c.getString(titleIndex) + "\" ("
1877 + cellX + "," + cellY + "@"
1878 + LauncherSettings.Favorites.containerToString(container)
1879 + "/" + screen
1880 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001881
1882 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001883
1884 final Intent intent;
1885 final ComponentName cn;
1886 try {
1887 intent = Intent.parseUri(intentStr, 0);
1888 } catch (URISyntaxException e) {
1889 // bogus intent?
1890 Launcher.addDumpLog(TAG,
1891 "skipping invalid intent uri", true);
1892 continue;
1893 }
1894
1895 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001896 if (TextUtils.isEmpty(intentStr)) {
1897 // no intent? no icon
1898 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1899 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001900 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001901 !LauncherModel.isValidPackageActivity(mContext, cn,
1902 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001903 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001904 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001905 "no longer exists.", true);
1906 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001907 } else if (container ==
1908 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1909 // Dedupe icons directly on the workspace
1910
Adam Cohen556f6132014-01-15 15:18:08 -08001911 // Canonicalize
1912 // the Play Store sets the package parameter, but Launcher
1913 // does not, so we clear that out to keep them the same
1914 intent.setPackage(null);
1915 final String key = intent.toUri(0);
1916 if (seenIntents.contains(key)) {
1917 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001918 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001919 } else {
1920 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001921 }
1922 }
1923 }
1924
1925 ContentValues values = new ContentValues(c.getColumnCount());
1926 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1927 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1928 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1929 values.put(LauncherSettings.Favorites.ICON_TYPE,
1930 c.getInt(iconTypeIndex));
1931 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1932 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1933 c.getString(iconPackageIndex));
1934 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1935 c.getString(iconResourceIndex));
1936 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1937 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1938 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1939 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1940 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001941 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001942
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001943 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1944 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001945 }
1946
1947 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1948 // In a folder or in the hotseat, preserve position
1949 values.put(LauncherSettings.Favorites.SCREEN, screen);
1950 values.put(LauncherSettings.Favorites.CELLX, cellX);
1951 values.put(LauncherSettings.Favorites.CELLY, cellY);
1952 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001953 // For items contained directly on one of the workspace screen,
1954 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001955 }
1956
1957 values.put(LauncherSettings.Favorites.CONTAINER, container);
1958
Adam Cohen72960972014-01-15 18:13:55 -08001959 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1960 shortcuts.add(values);
1961 } else {
1962 folders.add(values);
1963 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001964 }
1965
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001966 // Now that we have all the hotseat icons, let's go through them left-right
1967 // and assign valid locations for them in the new hotseat
1968 final int N = hotseat.size();
1969 for (int idx=0; idx<N; idx++) {
1970 int hotseatX = hotseat.keyAt(idx);
1971 ContentValues values = hotseat.valueAt(idx);
1972
1973 if (hotseatX == grid.hotseatAllAppsRank) {
1974 // let's drop this in the next available hole in the hotseat
1975 while (++hotseatX < hotseatWidth) {
1976 if (hotseat.get(hotseatX) == null) {
1977 // found a spot! move it here
1978 values.put(LauncherSettings.Favorites.SCREEN,
1979 hotseatX);
1980 break;
1981 }
1982 }
1983 }
1984 if (hotseatX >= hotseatWidth) {
1985 // no room for you in the hotseat? it's off to the desktop with you
1986 values.put(LauncherSettings.Favorites.CONTAINER,
1987 Favorites.CONTAINER_DESKTOP);
1988 }
1989 }
1990
Adam Cohen72960972014-01-15 18:13:55 -08001991 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1992 // Folders first
1993 allItems.addAll(folders);
1994 // Then shortcuts
1995 allItems.addAll(shortcuts);
1996
1997 // Layout all the folders
1998 for (ContentValues values: allItems) {
1999 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2000 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2001 // Hotseat items and folder items have already had their
2002 // location information set. Nothing to be done here.
2003 continue;
2004 }
2005 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2006 values.put(LauncherSettings.Favorites.CELLX, curX);
2007 values.put(LauncherSettings.Favorites.CELLY, curY);
2008 curX = (curX + 1) % width;
2009 if (curX == 0) {
2010 curY = (curY + 1);
2011 }
2012 // Leave the last row of icons blank on every screen
2013 if (curY == height - 1) {
2014 curScreen = (int) generateNewScreenId();
2015 curY = 0;
2016 }
2017 }
2018
2019 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002020 db.beginTransaction();
2021 try {
Adam Cohen72960972014-01-15 18:13:55 -08002022 for (ContentValues row: allItems) {
2023 if (row == null) continue;
2024 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002025 < 0) {
2026 return;
2027 } else {
2028 count++;
2029 }
2030 }
2031 db.setTransactionSuccessful();
2032 } finally {
2033 db.endTransaction();
2034 }
2035 }
2036
2037 db.beginTransaction();
2038 try {
2039 for (i=0; i<=curScreen; i++) {
2040 final ContentValues values = new ContentValues();
2041 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2042 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2043 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2044 < 0) {
2045 return;
2046 }
2047 }
2048 db.setTransactionSuccessful();
2049 } finally {
2050 db.endTransaction();
2051 }
2052 }
2053 } finally {
2054 c.close();
2055 }
2056 }
2057
2058 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2059 + (curScreen+1) + " screens", true);
2060
2061 // ensure that new screens are created to hold these icons
2062 setFlagJustLoadedOldDb();
2063
2064 // Update max IDs; very important since we just grabbed IDs from another database
2065 mMaxItemId = initializeMaxItemId(db);
2066 mMaxScreenId = initializeMaxScreenId(db);
2067 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2068 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002069 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002070
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002071 /**
2072 * Build a query string that will match any row where the column matches
2073 * anything in the values list.
2074 */
2075 static String buildOrWhereString(String column, int[] values) {
2076 StringBuilder selectWhere = new StringBuilder();
2077 for (int i = values.length - 1; i >= 0; i--) {
2078 selectWhere.append(column).append("=").append(values[i]);
2079 if (i > 0) {
2080 selectWhere.append(" OR ");
2081 }
2082 }
2083 return selectWhere.toString();
2084 }
2085
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002086 /**
2087 * Return attribute value, attempting launcher-specific namespace first
2088 * before falling back to anonymous attribute.
2089 */
2090 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2091 String value = parser.getAttributeValue(
2092 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2093 if (value == null) {
2094 value = parser.getAttributeValue(null, attribute);
2095 }
2096 return value;
2097 }
2098
2099 /**
2100 * Return attribute resource value, attempting launcher-specific namespace
2101 * first before falling back to anonymous attribute.
2102 */
2103 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2104 int defaultValue) {
2105 int value = parser.getAttributeResourceValue(
2106 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2107 defaultValue);
2108 if (value == defaultValue) {
2109 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2110 }
2111 return value;
2112 }
2113
2114 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2115 to.put(key, from.getAsInteger(key));
2116 }
2117
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002118 static class SqlArguments {
2119 public final String table;
2120 public final String where;
2121 public final String[] args;
2122
2123 SqlArguments(Uri url, String where, String[] args) {
2124 if (url.getPathSegments().size() == 1) {
2125 this.table = url.getPathSegments().get(0);
2126 this.where = where;
2127 this.args = args;
2128 } else if (url.getPathSegments().size() != 2) {
2129 throw new IllegalArgumentException("Invalid URI: " + url);
2130 } else if (!TextUtils.isEmpty(where)) {
2131 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2132 } else {
2133 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002134 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002135 this.args = null;
2136 }
2137 }
2138
2139 SqlArguments(Uri url) {
2140 if (url.getPathSegments().size() == 1) {
2141 table = url.getPathSegments().get(0);
2142 where = null;
2143 args = null;
2144 } else {
2145 throw new IllegalArgumentException("Invalid URI: " + url);
2146 }
2147 }
2148 }
Adam Cohen72960972014-01-15 18:13:55 -08002149}