blob: ac4a2063e791234e245d78850bf7153f19b7d718 [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;
Adam Cohen71483f42014-05-15 14:04:01 -070071import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050072import java.util.HashSet;
Bjorn Bringertcd8fec02010-01-14 13:26:43 +000073import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080076 private static final String TAG = "Launcher.LauncherProvider";
77 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
79 private static final String DATABASE_NAME = "launcher.db";
Winson Chung3d503fb2011-07-13 17:25:49 -070080
Kenny Guyed131872014-04-30 03:02:21 +010081 private static final int DATABASE_VERSION = 20;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
Adam Cohene25af792013-06-06 23:08:25 -070083 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040084 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070085
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050086 // Should we attempt to load anything from the com.android.launcher2 provider?
Dan Sandlerd5024042014-01-09 15:01:33 -050087 static final boolean IMPORT_LAUNCHER2_DATABASE = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -050088
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070090 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 static final String PARAMETER_NOTIFY = "notify";
Winson Chungc763c4e2013-07-19 13:49:06 -070092 static final String UPGRADED_FROM_OLD_DATABASE =
93 "UPGRADED_FROM_OLD_DATABASE";
94 static final String EMPTY_DATABASE_CREATED =
95 "EMPTY_DATABASE_CREATED";
Michael Jurka45355c42012-10-08 13:21:35 +020096 static final String DEFAULT_WORKSPACE_RESOURCE_ID =
97 "DEFAULT_WORKSPACE_RESOURCE_ID";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Winson Chungb3302ae2012-05-01 10:19:14 -070099 private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE =
Adam Cohene25af792013-06-06 23:08:25 -0700100 "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
Winson Chungb3302ae2012-05-01 10:19:14 -0700101
Adam Cohena043fa82014-07-23 14:49:38 -0700102 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
103
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700104 private LauncherProviderChangeListener mListener;
105
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700106 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700107 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700108 * {@link AppWidgetHost#deleteHost()} is called during database creation.
109 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
110 */
111 static final Uri CONTENT_APPWIDGET_RESET_URI =
112 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700113
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700114 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700115 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116
117 @Override
118 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400119 final Context context = getContext();
120 mOpenHelper = new DatabaseHelper(context);
121 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 return true;
123 }
124
Winson Chung0b560dd2014-01-21 13:00:26 -0800125 public boolean wasNewDbCreated() {
126 return mOpenHelper.wasNewDbCreated();
127 }
128
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700129 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
130 mListener = listener;
131 }
132
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 @Override
134 public String getType(Uri uri) {
135 SqlArguments args = new SqlArguments(uri, null, null);
136 if (TextUtils.isEmpty(args.where)) {
137 return "vnd.android.cursor.dir/" + args.table;
138 } else {
139 return "vnd.android.cursor.item/" + args.table;
140 }
141 }
142
143 @Override
144 public Cursor query(Uri uri, String[] projection, String selection,
145 String[] selectionArgs, String sortOrder) {
146
147 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
148 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
149 qb.setTables(args.table);
150
Romain Guy73b979d2009-06-09 12:57:21 -0700151 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
153 result.setNotificationUri(getContext().getContentResolver(), uri);
154
155 return result;
156 }
157
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 private static long dbInsertAndCheck(DatabaseHelper helper,
159 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500160 if (values == null) {
161 throw new RuntimeException("Error: attempting to insert null values");
162 }
Adam Cohen71483f42014-05-15 14:04:01 -0700163 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 throw new RuntimeException("Error: attempting to add item without specifying an id");
165 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500166 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700167 return db.insert(table, nullColumnHack, values);
168 }
169
Adam Cohen228da5a2011-07-27 22:23:47 -0700170 private static void deleteId(SQLiteDatabase db, long id) {
171 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
172 SqlArguments args = new SqlArguments(uri, null, null);
173 db.delete(args.table, args.where, args.args);
174 }
175
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176 @Override
177 public Uri insert(Uri uri, ContentValues initialValues) {
178 SqlArguments args = new SqlArguments(uri);
179
Adam Cohena043fa82014-07-23 14:49:38 -0700180 // In very limited cases, we support system|signature permission apps to add to the db
181 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
182 if (externalAdd != null && "true".equals(externalAdd)) {
183 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
184 return null;
185 }
186 }
187
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800188 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400189 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700190 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 if (rowId <= 0) return null;
192
193 uri = ContentUris.withAppendedId(uri, rowId);
194 sendNotify(uri);
195
196 return uri;
197 }
198
Adam Cohena043fa82014-07-23 14:49:38 -0700199
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 @Override
201 public int bulkInsert(Uri uri, ContentValues[] values) {
202 SqlArguments args = new SqlArguments(uri);
203
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 db.beginTransaction();
206 try {
207 int numValues = values.length;
208 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400209 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700210 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
211 return 0;
212 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 }
214 db.setTransactionSuccessful();
215 } finally {
216 db.endTransaction();
217 }
218
219 sendNotify(uri);
220 return values.length;
221 }
222
223 @Override
Yura085c8532014-02-11 15:15:29 +0000224 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
225 throws OperationApplicationException {
226 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
227 db.beginTransaction();
228 try {
229 ContentProviderResult[] result = super.applyBatch(operations);
230 db.setTransactionSuccessful();
231 return result;
232 } finally {
233 db.endTransaction();
234 }
235 }
236
237 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 public int delete(Uri uri, String selection, String[] selectionArgs) {
239 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
240
241 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
242 int count = db.delete(args.table, args.where, args.args);
243 if (count > 0) sendNotify(uri);
244
245 return count;
246 }
247
248 @Override
249 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
250 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
251
Chris Wren1ada10d2013-09-13 18:01:38 -0400252 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
254 int count = db.update(args.table, values, args.where, args.args);
255 if (count > 0) sendNotify(uri);
256
257 return count;
258 }
259
260 private void sendNotify(Uri uri) {
261 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
262 if (notify == null || "true".equals(notify)) {
263 getContext().getContentResolver().notifyChange(uri, null);
264 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400265
266 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400267 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700268 if (mListener != null) {
269 mListener.onLauncherProviderChange();
270 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400271 }
272
273 private void addModifiedTime(ContentValues values) {
274 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 }
276
Adam Cohendcd297f2013-06-18 13:13:40 -0700277 public long generateNewItemId() {
278 return mOpenHelper.generateNewItemId();
279 }
280
Winson Chungc763c4e2013-07-19 13:49:06 -0700281 public void updateMaxItemId(long id) {
282 mOpenHelper.updateMaxItemId(id);
283 }
284
Adam Cohendcd297f2013-06-18 13:13:40 -0700285 public long generateNewScreenId() {
286 return mOpenHelper.generateNewScreenId();
287 }
288
289 // This is only required one time while loading the workspace during the
290 // upgrade path, and should never be called from anywhere else.
291 public void updateMaxScreenId(long maxScreenId) {
292 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700293 }
294
Brian Muramatsu5524b492012-10-02 16:55:54 -0700295 /**
Adam Cohene25af792013-06-06 23:08:25 -0700296 * @param Should we load the old db for upgrade? first run only.
297 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700298 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400299 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700300 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
301
Winson Chungc763c4e2013-07-19 13:49:06 -0700302 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700303
Winson Chungc763c4e2013-07-19 13:49:06 -0700304 sJustLoadedFromOldDb = false;
305 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700306
307 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700308 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700309 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700310 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700311 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700312 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700313 }
314
315 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700316 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
317 */
Michael Jurka45355c42012-10-08 13:21:35 +0200318 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400319 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700320 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700321
Winson Chungc763c4e2013-07-19 13:49:06 -0700322 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500323 Log.d(TAG, "loading default workspace");
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700324 // By default we use our resources
325 Resources res = getContext().getResources();
Michael Jurka45355c42012-10-08 13:21:35 +0200326 int workspaceResId = origWorkspaceResId;
327
Brian Muramatsu5524b492012-10-02 16:55:54 -0700328 // Use default workspace resource if none provided
329 if (workspaceResId == 0) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700330 final Partner partner = Partner.get(getContext().getPackageManager());
331 if (partner != null && partner.hasDefaultLayout()) {
332 final Resources partnerRes = partner.getResources();
333 workspaceResId = partnerRes.getIdentifier(Partner.RESOURCE_DEFAULT_LAYOUT,
334 "xml", partner.getPackageName());
335 res = partnerRes;
336 }
337 }
338 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800339 workspaceResId =
340 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700341 }
342
Michael Jurkab85f8a42012-04-25 15:48:32 -0700343 // Populate favorites table with initial favorites
344 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700345 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200346 if (origWorkspaceResId != 0) {
347 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
348 }
Adam Cohene25af792013-06-06 23:08:25 -0700349
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700350 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), res, workspaceResId);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700351 editor.commit();
352 }
353 }
354
Dan Sandlerd5024042014-01-09 15:01:33 -0500355 public void migrateLauncher2Shortcuts() {
356 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400357 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500358 }
359
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800360 private static int getDefaultWorkspaceResourceId() {
Winson Chungbe876472014-05-14 14:15:20 -0700361 LauncherAppState app = LauncherAppState.getInstance();
362 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800363 if (LauncherAppState.isDisableAllApps()) {
Winson Chungbe876472014-05-14 14:15:20 -0700364 return grid.defaultNoAllAppsLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800365 } else {
Winson Chungbe876472014-05-14 14:15:20 -0700366 return grid.defaultLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800367 }
368 }
369
Winson Chungc763c4e2013-07-19 13:49:06 -0700370 private static interface ContentValuesCallback {
371 public void onRow(ContentValues values);
372 }
373
Adam Cohen6dbe0492013-12-02 17:00:14 -0800374 private static boolean shouldImportLauncher2Database(Context context) {
375 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
376
377 // We don't import the old databse for tablets, as the grid size has changed.
378 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
379 }
380
Dan Sandlerd5024042014-01-09 15:01:33 -0500381 public void deleteDatabase() {
382 // Are you sure? (y/n)
383 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500384 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500385 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500386 if (dbFile.exists()) {
387 SQLiteDatabase.deleteDatabase(dbFile);
388 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500389 mOpenHelper = new DatabaseHelper(getContext());
390 }
391
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800392 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500393 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 private static final String TAG_FAVORITES = "favorites";
395 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700396 private static final String TAG_CLOCK = "clock";
397 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700398 private static final String TAG_APPWIDGET = "appwidget";
399 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700400 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700401 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700402 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400403 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700404
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700405 // Style attrs -- "Favorite"
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700406 private static final String ATTR_CLASS_NAME = "className";
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700407 private static final String ATTR_PACKAGE_NAME = "packageName";
408 private static final String ATTR_CONTAINER = "container";
409 private static final String ATTR_SCREEN = "screen";
410 private static final String ATTR_X = "x";
411 private static final String ATTR_Y = "y";
412 private static final String ATTR_SPAN_X = "spanX";
413 private static final String ATTR_SPAN_Y = "spanY";
414 private static final String ATTR_ICON = "icon";
415 private static final String ATTR_TITLE = "title";
416 private static final String ATTR_URI = "uri";
417
418 // Style attrs -- "Include"
419 private static final String ATTR_WORKSPACE = "workspace";
420
421 // Style attrs -- "Extra"
422 private static final String ATTR_KEY = "key";
423 private static final String ATTR_VALUE = "value";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700424
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700426 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700427 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700428 private long mMaxItemId = -1;
429 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800430
Winson Chung0b560dd2014-01-21 13:00:26 -0800431 private boolean mNewDbCreated = false;
432
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800433 DatabaseHelper(Context context) {
434 super(context, DATABASE_NAME, null, DATABASE_VERSION);
435 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700436 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700437 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700438
439 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
440 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700441 if (mMaxItemId == -1) {
442 mMaxItemId = initializeMaxItemId(getWritableDatabase());
443 }
444 if (mMaxScreenId == -1) {
445 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700446 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800447 }
448
Winson Chung0b560dd2014-01-21 13:00:26 -0800449 public boolean wasNewDbCreated() {
450 return mNewDbCreated;
451 }
452
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700453 /**
454 * Send notification that we've deleted the {@link AppWidgetHost},
455 * probably as part of the initial database creation. The receiver may
456 * want to re-call {@link AppWidgetHost#startListening()} to ensure
457 * callbacks are correctly set.
458 */
459 private void sendAppWidgetResetNotify() {
460 final ContentResolver resolver = mContext.getContentResolver();
461 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
462 }
463
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800464 @Override
465 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800466 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700467
Adam Cohendcd297f2013-06-18 13:13:40 -0700468 mMaxItemId = 1;
469 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800470 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700471
Kenny Guyed131872014-04-30 03:02:21 +0100472 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
473 long userSerialNumber = userManager.getSerialNumberForUser(
474 UserHandleCompat.myUserHandle());
475
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800476 db.execSQL("CREATE TABLE favorites (" +
477 "_id INTEGER PRIMARY KEY," +
478 "title TEXT," +
479 "intent TEXT," +
480 "container INTEGER," +
481 "screen INTEGER," +
482 "cellX INTEGER," +
483 "cellY INTEGER," +
484 "spanX INTEGER," +
485 "spanY INTEGER," +
486 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700487 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800488 "isShortcut INTEGER," +
489 "iconType INTEGER," +
490 "iconPackage TEXT," +
491 "iconResource TEXT," +
492 "icon BLOB," +
493 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400494 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400495 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500496 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100497 "restored INTEGER NOT NULL DEFAULT 0," +
498 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800499 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700500 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800501
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700502 // Database was just created, so wipe any previous widgets
503 if (mAppWidgetHost != null) {
504 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700505 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800506 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700507
Adam Cohen6dbe0492013-12-02 17:00:14 -0800508 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500509 // Try converting the old database
510 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
511 public void onRow(ContentValues values) {
512 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
513 if (container == Favorites.CONTAINER_DESKTOP) {
514 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
515 screen = (int) upgradeLauncherDb_permuteScreens(screen);
516 values.put(LauncherSettings.Favorites.SCREEN, screen);
517 }
518 }
519 };
520 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
521 "/old_favorites?notify=true");
522 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
523 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400524 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500525 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
526 // If we fail, then set a flag to load the default workspace
527 setFlagEmptyDbCreated();
528 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700529 }
530 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500531 // Right now, in non-default workspace cases, we want to run the final
532 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
533 // set that flag too.
534 setFlagJustLoadedOldDb();
535 } else {
536 // Fresh and clean launcher DB.
537 mMaxItemId = initializeMaxItemId(db);
538 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800539 }
540 }
541
Adam Cohendcd297f2013-06-18 13:13:40 -0700542 private void addWorkspacesTable(SQLiteDatabase db) {
543 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
544 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400545 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
546 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700547 ");");
548 }
549
Adam Cohen119285e2014-04-02 16:59:08 -0700550 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700551 // Delete items directly on the workspace who's screen id doesn't exist
552 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
553 // AND container = -100"
554 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
555 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700556 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700557 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
558 " AND " +
559 LauncherSettings.Favorites.CONTAINER + " = " +
560 LauncherSettings.Favorites.CONTAINER_DESKTOP;
561 db.execSQL(removeOrphanedDesktopItems);
562
563 // Delete items contained in folders which no longer exist (after above statement)
564 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
565 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
566 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
567 " WHERE " +
568 LauncherSettings.Favorites.CONTAINER + " <> " +
569 LauncherSettings.Favorites.CONTAINER_DESKTOP +
570 " AND "
571 + LauncherSettings.Favorites.CONTAINER + " <> " +
572 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
573 " AND "
574 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
575 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
576 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
577 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
578 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700579 }
580
Winson Chungc763c4e2013-07-19 13:49:06 -0700581 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400582 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700583 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
584 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700585 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
586 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700587 editor.commit();
588 }
589
Winson Chungc763c4e2013-07-19 13:49:06 -0700590 private void setFlagEmptyDbCreated() {
591 String spKey = LauncherAppState.getSharedPreferencesKey();
592 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
593 SharedPreferences.Editor editor = sp.edit();
594 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
595 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
596 editor.commit();
597 }
598
599 // We rearrange the screens from the old launcher
600 // 12345 -> 34512
601 private long upgradeLauncherDb_permuteScreens(long screen) {
602 if (screen >= 2) {
603 return screen - 2;
604 } else {
605 return screen + 3;
606 }
607 }
608
609 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
610 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800611 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612 boolean converted = false;
613
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 final ContentResolver resolver = mContext.getContentResolver();
615 Cursor cursor = null;
616
617 try {
618 cursor = resolver.query(uri, null, null, null, null);
619 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700620 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 }
622
623 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700624 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700626 if (cursor.getCount() > 0) {
627 converted = copyFromCursor(db, cursor, cb) > 0;
628 if (converted && deleteRows) {
629 resolver.delete(uri, null, null);
630 }
631 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632 } finally {
633 cursor.close();
634 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700636
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700638 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800639 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700641
642 // Update max item id
643 mMaxItemId = initializeMaxItemId(db);
644 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 }
646
647 return converted;
648 }
649
Winson Chungc763c4e2013-07-19 13:49:06 -0700650 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700651 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
653 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
654 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
655 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
656 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
657 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
658 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
659 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
660 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
661 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
662 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
663 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
664 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
665
666 ContentValues[] rows = new ContentValues[c.getCount()];
667 int i = 0;
668 while (c.moveToNext()) {
669 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700670 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800671 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
672 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
673 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
674 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
675 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
676 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
677 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
678 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700679 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800680 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
681 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
682 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
683 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
684 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700685 if (cb != null) {
686 cb.onRow(values);
687 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688 rows[i++] = values;
689 }
690
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700692 if (i > 0) {
693 db.beginTransaction();
694 try {
695 int numValues = rows.length;
696 for (i = 0; i < numValues; i++) {
697 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
698 return 0;
699 } else {
700 total++;
701 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800702 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700703 db.setTransactionSuccessful();
704 } finally {
705 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800706 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707 }
708
709 return total;
710 }
711
712 @Override
713 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700714 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700715
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700717 if (version < 3) {
718 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800719 db.beginTransaction();
720 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700721 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800722 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700723 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800724 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700725 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800726 } catch (SQLException ex) {
727 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800728 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800729 } finally {
730 db.endTransaction();
731 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700732
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800733 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700734 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800735 convertWidgets(db);
736 }
737 }
Romain Guy73b979d2009-06-09 12:57:21 -0700738
739 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800740 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700741 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700742
Romain Guy509cd6a2010-03-23 15:10:56 -0700743 // Where's version 5?
744 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400745 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700746 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
747 // but version 5 on there was the updateContactsShortcuts change
748 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
749 // The updateContactsShortcuts change is idempotent, so running it twice
750 // is okay so we'll do that when upgrading the devices that shipped with it.
751 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800752 // We went from 3 to 5 screens. Move everything 1 to the right
753 db.beginTransaction();
754 try {
755 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
756 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800757 } catch (SQLException ex) {
758 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800759 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800760 } finally {
761 db.endTransaction();
762 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700763
Romain Guy509cd6a2010-03-23 15:10:56 -0700764 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800765 if (updateContactsShortcuts(db)) {
766 version = 6;
767 }
768 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000769
770 if (version < 7) {
771 // Version 7 gets rid of the special search widget.
772 convertWidgets(db);
773 version = 7;
774 }
775
Joe Onorato0589f0f2010-02-08 13:44:00 -0800776 if (version < 8) {
777 // Version 8 (froyo) has the icons all normalized. This should
778 // already be the case in practice, but we now rely on it and don't
779 // resample the images each time.
780 normalizeIcons(db);
781 version = 8;
782 }
783
Winson Chung3d503fb2011-07-13 17:25:49 -0700784 if (version < 9) {
785 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
786 // 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 -0700787 if (mMaxItemId == -1) {
788 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700789 }
790
791 // Add default hotseat icons
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700792 loadFavorites(db, mContext.getResources(), R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700793 version = 9;
794 }
795
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700796 // We bumped the version three time during JB, once to update the launch flags, once to
797 // update the override for the default launch animation and once to set the mimetype
798 // to improve startup performance
799 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700800 // Contact shortcuts need a different set of flags to be launched now
801 // The updateContactsShortcuts change is idempotent, so we can keep using it like
802 // back in the Donut days
803 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700804 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700805 }
806
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 if (version < 13) {
808 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
809 // to persist workspace screens and their relative order.
810 mMaxScreenId = 0;
811
812 // This will never happen in the wild, but when we switch to using workspace
813 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700814 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700815
816 addWorkspacesTable(db);
817 version = 13;
818 }
819
Chris Wrend5e66bf2013-09-16 14:02:29 -0400820 if (version < 14) {
821 db.beginTransaction();
822 try {
823 // Insert new column for holding widget provider name
824 db.execSQL("ALTER TABLE favorites " +
825 "ADD COLUMN appWidgetProvider TEXT;");
826 db.setTransactionSuccessful();
827 version = 14;
828 } catch (SQLException ex) {
829 // Old version remains, which means we wipe old data
830 Log.e(TAG, ex.getMessage(), ex);
831 } finally {
832 db.endTransaction();
833 }
834 }
835
Chris Wren1ada10d2013-09-13 18:01:38 -0400836 if (version < 15) {
837 db.beginTransaction();
838 try {
839 // Insert new column for holding update timestamp
840 db.execSQL("ALTER TABLE favorites " +
841 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
842 db.execSQL("ALTER TABLE workspaceScreens " +
843 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
844 db.setTransactionSuccessful();
845 version = 15;
846 } catch (SQLException ex) {
847 // Old version remains, which means we wipe old data
848 Log.e(TAG, ex.getMessage(), ex);
849 } finally {
850 db.endTransaction();
851 }
852 }
853
Chris Wrenf4d08112014-01-16 18:13:56 -0500854
855 if (version < 16) {
856 db.beginTransaction();
857 try {
858 // Insert new column for holding restore status
859 db.execSQL("ALTER TABLE favorites " +
860 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
861 db.setTransactionSuccessful();
862 version = 16;
863 } catch (SQLException ex) {
864 // Old version remains, which means we wipe old data
865 Log.e(TAG, ex.getMessage(), ex);
866 } finally {
867 db.endTransaction();
868 }
869 }
870
Adam Cohen71e03b92014-02-21 14:09:53 -0800871 if (version < 17) {
872 // We use the db version upgrade here to identify users who may not have seen
873 // clings yet (because they weren't available), but for whom the clings are now
874 // available (tablet users). Because one of the possible cling flows (migration)
875 // is very destructive (wipes out workspaces), we want to prevent this from showing
876 // until clear data. We do so by marking that the clings have been shown.
877 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
878 version = 17;
879 }
880
Adam Cohen119285e2014-04-02 16:59:08 -0700881 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700882 // No-op
883 version = 18;
884 }
885
886 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700887 // Due to a data loss bug, some users may have items associated with screen ids
888 // which no longer exist. Since this can cause other problems, and since the user
889 // will never see these items anyway, we use database upgrade as an opportunity to
890 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700891 removeOrphanedItems(db);
892 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700893 }
894
Kenny Guyed131872014-04-30 03:02:21 +0100895 if (version < 20) {
896 // Add userId column
897 if (addProfileColumn(db)) {
898 version = 20;
899 }
900 // else old version remains, which means we wipe old data
901 }
902
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800903 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800904 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800905 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700906 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
907
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800908 onCreate(db);
909 }
910 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800911
Adam Cohen9b1d0622014-05-21 19:01:57 -0700912 @Override
913 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
914 // This shouldn't happen -- throw our hands up in the air and start over.
915 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
916 ". Wiping databse.");
917
918 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
919 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
920 onCreate(db);
921 }
922
Kenny Guyed131872014-04-30 03:02:21 +0100923 private boolean addProfileColumn(SQLiteDatabase db) {
924 db.beginTransaction();
925 try {
926 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
927 // Default to the serial number of this user, for older
928 // shortcuts.
929 long userSerialNumber = userManager.getSerialNumberForUser(
930 UserHandleCompat.myUserHandle());
931 // Insert new column for holding user serial number
932 db.execSQL("ALTER TABLE favorites " +
933 "ADD COLUMN profileId INTEGER DEFAULT "
934 + userSerialNumber + ";");
935 db.setTransactionSuccessful();
936 } catch (SQLException ex) {
937 // Old version remains, which means we wipe old data
938 Log.e(TAG, ex.getMessage(), ex);
939 return false;
940 } finally {
941 db.endTransaction();
942 }
943 return true;
944 }
945
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800946 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800947 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
948 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
949
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700950 Cursor c = null;
951 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800952 db.beginTransaction();
953 try {
954 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700955 c = db.query(TABLE_FAVORITES,
956 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800957 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700958 if (c == null) return false;
959
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800960 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700961
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800962 final int idIndex = c.getColumnIndex(Favorites._ID);
963 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700964
965 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800966 long favoriteId = c.getLong(idIndex);
967 final String intentUri = c.getString(intentIndex);
968 if (intentUri != null) {
969 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700970 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800971 android.util.Log.d("Home", intent.toString());
972 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700973 if (uri != null) {
974 final String data = uri.toString();
975 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
976 actionQuickContact.equals(intent.getAction())) &&
977 (data.startsWith("content://contacts/people/") ||
978 data.startsWith("content://com.android.contacts/" +
979 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800980
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700981 final Intent newIntent = new Intent(actionQuickContact);
982 // When starting from the launcher, start in a new, cleared task
983 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
984 // clear the whole thing preemptively here since
985 // QuickContactActivity will finish itself when launching other
986 // detail activities.
987 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
988 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700989 newIntent.putExtra(
990 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700991 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700992 // Determine the type and also put that in the shortcut
993 // (that can speed up launch a bit)
994 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800995
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700996 final ContentValues values = new ContentValues();
997 values.put(LauncherSettings.Favorites.INTENT,
998 newIntent.toUri(0));
999
1000 String updateWhere = Favorites._ID + "=" + favoriteId;
1001 db.update(TABLE_FAVORITES, values, updateWhere, null);
1002 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001003 }
1004 } catch (RuntimeException ex) {
1005 Log.e(TAG, "Problem upgrading shortcut", ex);
1006 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001007 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001008 }
1009 }
1010 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001011
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001012 db.setTransactionSuccessful();
1013 } catch (SQLException ex) {
1014 Log.w(TAG, "Problem while upgrading contacts", ex);
1015 return false;
1016 } finally {
1017 db.endTransaction();
1018 if (c != null) {
1019 c.close();
1020 }
1021 }
1022
1023 return true;
1024 }
1025
Joe Onorato0589f0f2010-02-08 13:44:00 -08001026 private void normalizeIcons(SQLiteDatabase db) {
1027 Log.d(TAG, "normalizing icons");
1028
Joe Onorato346e1292010-02-18 10:34:24 -05001029 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001030 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -04001031 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001032 try {
1033 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -04001034 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -06001035 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -08001036
1037 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
1038 Favorites.ICON_TYPE_BITMAP, null);
1039
1040 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1041 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
1042
1043 while (c.moveToNext()) {
1044 long id = c.getLong(idIndex);
1045 byte[] data = c.getBlob(iconIndex);
1046 try {
1047 Bitmap bitmap = Utilities.resampleIconBitmap(
1048 BitmapFactory.decodeByteArray(data, 0, data.length),
1049 mContext);
1050 if (bitmap != null) {
1051 update.bindLong(1, id);
1052 data = ItemInfo.flattenBitmap(bitmap);
1053 if (data != null) {
1054 update.bindBlob(2, data);
1055 update.execute();
1056 }
1057 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001058 }
1059 } catch (Exception e) {
1060 if (!logged) {
1061 Log.e(TAG, "Failed normalizing icon " + id, e);
1062 } else {
1063 Log.e(TAG, "Also failed normalizing icon " + id);
1064 }
1065 logged = true;
1066 }
1067 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001068 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001069 } catch (SQLException ex) {
1070 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1071 } finally {
1072 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001073 if (update != null) {
1074 update.close();
1075 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001076 if (c != null) {
1077 c.close();
1078 }
1079 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001080 }
1081
1082 // Generates a new ID to use for an object in your database. This method should be only
1083 // called from the main UI thread. As an exception, we do call it when we call the
1084 // constructor from the worker thread; however, this doesn't extend until after the
1085 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1086 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001087 public long generateNewItemId() {
1088 if (mMaxItemId < 0) {
1089 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001091 mMaxItemId += 1;
1092 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001093 }
1094
Winson Chungc763c4e2013-07-19 13:49:06 -07001095 public void updateMaxItemId(long id) {
1096 mMaxItemId = id + 1;
1097 }
1098
Chris Wren5dee7af2013-12-20 17:22:11 -05001099 public void checkId(String table, ContentValues values) {
1100 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1101 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1102 mMaxScreenId = Math.max(id, mMaxScreenId);
1103 } else {
1104 mMaxItemId = Math.max(id, mMaxItemId);
1105 }
1106 }
1107
Adam Cohendcd297f2013-06-18 13:13:40 -07001108 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001109 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1110
1111 // get the result
1112 final int maxIdIndex = 0;
1113 long id = -1;
1114 if (c != null && c.moveToNext()) {
1115 id = c.getLong(maxIdIndex);
1116 }
Michael Jurka5130e402011-10-13 04:55:35 -07001117 if (c != null) {
1118 c.close();
1119 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001120
1121 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001122 throw new RuntimeException("Error: could not query max item id");
1123 }
1124
1125 return id;
1126 }
1127
1128 // Generates a new ID to use for an workspace screen in your database. This method
1129 // should be only called from the main UI thread. As an exception, we do call it when we
1130 // call the constructor from the worker thread; however, this doesn't extend until after the
1131 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1132 // after that point
1133 public long generateNewScreenId() {
1134 if (mMaxScreenId < 0) {
1135 throw new RuntimeException("Error: max screen id was not initialized");
1136 }
1137 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001138 // Log to disk
1139 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 return mMaxScreenId;
1141 }
1142
1143 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001144 // Log to disk
1145 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001146 mMaxScreenId = maxScreenId;
1147 }
1148
1149 private long initializeMaxScreenId(SQLiteDatabase db) {
1150 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1151
1152 // get the result
1153 final int maxIdIndex = 0;
1154 long id = -1;
1155 if (c != null && c.moveToNext()) {
1156 id = c.getLong(maxIdIndex);
1157 }
1158 if (c != null) {
1159 c.close();
1160 }
1161
1162 if (id == -1) {
1163 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001164 }
1165
Winson Chunga90303b2013-11-15 13:05:06 -08001166 // Log to disk
1167 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001168 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001169 }
1170
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001172 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001173 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001174 */
1175 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001176 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001177 final int[] bindSources = new int[] {
1178 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1179 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001180 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001182
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001183 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001184
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001185 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001186
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001187 db.beginTransaction();
1188 try {
1189 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001190 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001191 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001192
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001193 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001194
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001195 final ContentValues values = new ContentValues();
1196 while (c != null && c.moveToNext()) {
1197 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001198 int favoriteType = c.getInt(1);
1199
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001200 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001201 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001202 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001203
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001204 if (LOGD) {
1205 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1206 + " for favoriteId=" + favoriteId);
1207 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001209 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1210 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1211
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001212 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001213 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1214 values.put(LauncherSettings.Favorites.SPANX, 4);
1215 values.put(LauncherSettings.Favorites.SPANY, 1);
1216 } else {
1217 values.put(LauncherSettings.Favorites.SPANX, 2);
1218 values.put(LauncherSettings.Favorites.SPANY, 2);
1219 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001220
1221 String updateWhere = Favorites._ID + "=" + favoriteId;
1222 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001223
Bjorn Bringert34251342009-12-15 13:33:11 +00001224 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001225 // TODO: check return value
1226 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001227 new ComponentName("com.android.alarmclock",
1228 "com.android.alarmclock.AnalogAppWidgetProvider"));
1229 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001230 // TODO: check return value
1231 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001232 new ComponentName("com.android.camera",
1233 "com.android.camera.PhotoAppWidgetProvider"));
1234 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001235 // TODO: check return value
1236 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001237 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001238 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001239 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001240 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001241 }
1242 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001243
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001244 db.setTransactionSuccessful();
1245 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001246 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001247 } finally {
1248 db.endTransaction();
1249 if (c != null) {
1250 c.close();
1251 }
1252 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001253
1254 // Update max item id
1255 mMaxItemId = initializeMaxItemId(db);
1256 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001257 }
1258
Adam Cohena043fa82014-07-23 14:49:38 -07001259 private boolean initializeExternalAdd(ContentValues values) {
1260 // 1. Ensure that externally added items have a valid item id
1261 long id = generateNewItemId();
1262 values.put(LauncherSettings.Favorites._ID, id);
1263
1264 // 2. In the case of an app widget, and if no app widget id is specified, we
1265 // attempt allocate and bind the widget.
1266 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1267 if (itemType != null &&
1268 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1269 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1270
1271 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1272 ComponentName cn = ComponentName.unflattenFromString(
1273 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1274
1275 if (cn != null) {
1276 try {
1277 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001278 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
1279 if (appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
1280 return true;
Adam Cohena043fa82014-07-23 14:49:38 -07001281 }
1282 } catch (RuntimeException e) {
1283 Log.e(TAG, "Failed to initialize external widget", e);
Adam Cohena043fa82014-07-23 14:49:38 -07001284 }
1285 }
Adam Cohen3ed316a2014-07-23 18:21:20 -07001286 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001287 }
1288 return true;
1289 }
1290
Michael Jurka8b805b12012-04-18 14:23:14 -07001291 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1292 throws XmlPullParserException, IOException {
1293 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001294 while ((type = parser.next()) != XmlPullParser.START_TAG
1295 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001296 ;
1297 }
1298
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001299 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001300 throw new XmlPullParserException("No start tag found");
1301 }
1302
1303 if (!parser.getName().equals(firstElementName)) {
1304 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1305 ", expected " + firstElementName);
1306 }
1307 }
1308
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001309 private static Intent buildMainIntent() {
1310 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1311 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1312 return intent;
1313 }
1314
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001315 private int loadFavorites(SQLiteDatabase db, Resources res, int workspaceResourceId) {
Adam Cohen71483f42014-05-15 14:04:01 -07001316 ArrayList<Long> screenIds = new ArrayList<Long>();
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001317 int count = loadFavoritesRecursive(db, res, workspaceResourceId, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001318
1319 // Add the screens specified by the items above
1320 Collections.sort(screenIds);
1321 int rank = 0;
1322 ContentValues values = new ContentValues();
1323 for (Long id : screenIds) {
1324 values.clear();
1325 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1326 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1327 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1328 throw new RuntimeException("Failed initialize screen table"
1329 + "from default layout");
1330 }
1331 rank++;
1332 }
1333
1334 // Ensure that the max ids are initialized
1335 mMaxItemId = initializeMaxItemId(db);
1336 mMaxScreenId = initializeMaxScreenId(db);
1337 return count;
1338 }
1339
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001340 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001341 * Loads the default set of favorite packages from an xml file.
1342 *
1343 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001344 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001345 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001346 */
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001347 private int loadFavoritesRecursive(SQLiteDatabase db, Resources res, int workspaceResourceId,
Adam Cohen71483f42014-05-15 14:04:01 -07001348 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001349
Adam Cohen71483f42014-05-15 14:04:01 -07001350 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001351 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1352
Adam Cohen71483f42014-05-15 14:04:01 -07001353 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001354 try {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001355 XmlResourceParser parser = res.getXml(workspaceResourceId);
Michael Jurka8b805b12012-04-18 14:23:14 -07001356 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001357
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001358 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001359
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001360 int type;
1361 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1362 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1363
1364 if (type != XmlPullParser.START_TAG) {
1365 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001366 }
1367
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001368 boolean added = false;
1369 final String name = parser.getName();
1370
Daniel Sandler57dac262013-10-03 13:28:36 -04001371 if (TAG_INCLUDE.equals(name)) {
Daniel Sandler57dac262013-10-03 13:28:36 -04001372
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001373 final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
Daniel Sandler57dac262013-10-03 13:28:36 -04001374
1375 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1376 "", resId));
1377
1378 if (resId != 0 && resId != workspaceResourceId) {
1379 // recursively load some more favorites, why not?
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001380 count += loadFavoritesRecursive(db, res, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001381 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001382 } else {
1383 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1384 }
1385
Daniel Sandler57dac262013-10-03 13:28:36 -04001386 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1387 continue;
1388 }
1389
1390 // Assuming it's a <favorite> at this point
Winson Chung3d503fb2011-07-13 17:25:49 -07001391 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001392 String strContainer = getAttributeValue(parser, ATTR_CONTAINER);
1393 if (strContainer != null) {
1394 container = Long.valueOf(strContainer);
Winson Chung3d503fb2011-07-13 17:25:49 -07001395 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001396
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001397 String screen = getAttributeValue(parser, ATTR_SCREEN);
1398 String x = getAttributeValue(parser, ATTR_X);
1399 String y = getAttributeValue(parser, ATTR_Y);
Winson Chung6d092682011-11-16 18:43:26 -08001400
Winson Chung6d092682011-11-16 18:43:26 -08001401 values.clear();
1402 values.put(LauncherSettings.Favorites.CONTAINER, container);
1403 values.put(LauncherSettings.Favorites.SCREEN, screen);
1404 values.put(LauncherSettings.Favorites.CELLX, x);
1405 values.put(LauncherSettings.Favorites.CELLY, y);
1406
Daniel Sandler57dac262013-10-03 13:28:36 -04001407 if (LOGD) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001408 final String title = getAttributeValue(parser, ATTR_TITLE);
1409 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
Daniel Sandler57dac262013-10-03 13:28:36 -04001410 final String something = title != null ? title : pkg;
1411 Log.v(TAG, String.format(
1412 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1413 "", name,
1414 (something == null ? "" : (" \"" + something + "\"")),
1415 container, screen, x, y));
1416 }
1417
Winson Chung6d092682011-11-16 18:43:26 -08001418 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001419 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001420 added = id >= 0;
Winson Chung6d092682011-11-16 18:43:26 -08001421 } else if (TAG_APPWIDGET.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001422 added = addAppWidget(parser, type, db, values);
Winson Chung6d092682011-11-16 18:43:26 -08001423 } else if (TAG_SHORTCUT.equals(name)) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001424 long id = addUriShortcut(db, values, res, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001425 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001426 } else if (TAG_RESOLVE.equals(name)) {
1427 // This looks through the contained favorites (or meta-favorites) and
1428 // attempts to add them as shortcuts in the fallback group's location
1429 // until one is added successfully.
1430 added = false;
1431 final int groupDepth = parser.getDepth();
1432 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1433 parser.getDepth() > groupDepth) {
1434 if (type != XmlPullParser.START_TAG) {
1435 continue;
1436 }
1437 final String fallback_item_name = parser.getName();
Jason Monk41314972014-03-03 16:11:30 -05001438 if (!added) {
1439 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001440 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001441 added = id >= 0;
1442 } else {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001443 Log.e(TAG, "Fallback groups can contain only favorites, found "
1444 + fallback_item_name);
Jason Monk41314972014-03-03 16:11:30 -05001445 }
1446 }
Jason Monk41314972014-03-03 16:11:30 -05001447 }
Winson Chung6d092682011-11-16 18:43:26 -08001448 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001449 // Folder contents are nested in this XML file
1450 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001451
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001452 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1453 // Folder contents come from an external XML resource
1454 final Partner partner = Partner.get(mPackageManager);
1455 if (partner != null) {
1456 final Resources partnerRes = partner.getResources();
1457 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1458 "xml", partner.getPackageName());
1459 if (resId != 0) {
1460 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1461 beginDocument(partnerParser, TAG_FOLDER);
1462 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001463 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001464 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001465 }
Adam Cohen71483f42014-05-15 14:04:01 -07001466 if (added) {
1467 long screenId = Long.parseLong(screen);
1468 // Keep track of the set of screens which need to be added to the db.
1469 if (!screenIds.contains(screenId) &&
1470 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1471 screenIds.add(screenId);
1472 }
1473 count++;
1474 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001475 }
1476 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001477 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001478 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001479 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001480 } catch (RuntimeException e) {
1481 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001482 }
Adam Cohen71483f42014-05-15 14:04:01 -07001483 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001484 }
1485
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001486 /**
1487 * Parse folder starting at current {@link XmlPullParser} location.
1488 */
1489 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1490 XmlResourceParser parser) throws IOException, XmlPullParserException {
1491 final String title;
1492 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1493 if (titleResId != 0) {
1494 title = res.getString(titleResId);
1495 } else {
1496 title = mContext.getResources().getString(R.string.folder_name);
1497 }
1498
1499 values.put(LauncherSettings.Favorites.TITLE, title);
1500 long folderId = addFolder(db, values);
1501 boolean added = folderId >= 0;
1502
1503 ArrayList<Long> folderItems = new ArrayList<Long>();
1504
1505 int type;
1506 int folderDepth = parser.getDepth();
1507 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1508 parser.getDepth() > folderDepth) {
1509 if (type != XmlPullParser.START_TAG) {
1510 continue;
1511 }
1512 final String tag = parser.getName();
1513
1514 final ContentValues childValues = new ContentValues();
1515 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1516
1517 if (LOGD) {
1518 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1519 final String uri = getAttributeValue(parser, ATTR_URI);
1520 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1521 tag, uri != null ? uri : pkg));
1522 }
1523
1524 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1525 final long id = addAppShortcut(db, childValues, parser);
1526 if (id >= 0) {
1527 folderItems.add(id);
1528 }
1529 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1530 final long id = addUriShortcut(db, childValues, res, parser);
1531 if (id >= 0) {
1532 folderItems.add(id);
1533 }
1534 } else {
1535 throw new RuntimeException("Folders can contain only shortcuts");
1536 }
1537 }
1538
1539 // We can only have folders with >= 2 items, so we need to remove the
1540 // folder and clean up if less than 2 items were included, or some
1541 // failed to add, and less than 2 were actually added
1542 if (folderItems.size() < 2 && folderId >= 0) {
1543 // Delete the folder
1544 deleteId(db, folderId);
1545
1546 // If we have a single item, promote it to where the folder
1547 // would have been.
1548 if (folderItems.size() == 1) {
1549 final ContentValues childValues = new ContentValues();
1550 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1551 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1552 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1553 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1554
1555 final long id = folderItems.get(0);
1556 db.update(TABLE_FAVORITES, childValues,
1557 LauncherSettings.Favorites._ID + "=" + id, null);
1558 } else {
1559 added = false;
1560 }
1561 }
1562 return added;
1563 }
1564
Jason Monk41314972014-03-03 16:11:30 -05001565 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1566 // logical choice for what shortcut should be used for that intent exists, then it is
1567 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001568 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1569 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001570 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001571 try {
Jason Monk41314972014-03-03 16:11:30 -05001572 metaIntent = Intent.parseUri(intentUri, 0);
1573 } catch (URISyntaxException e) {
1574 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1575 return -1;
1576 }
1577
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001578 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001579 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001580 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001581 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1582
1583 // Verify that the result is an app and not just the resolver dialog asking which
1584 // app to use.
1585 if (wouldLaunchResolverActivity(resolved, appList)) {
1586 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001587 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001588 if (systemApp == null) {
1589 // There is no logical choice for this meta-favorite, so rather than making
1590 // a bad choice just add nothing.
1591 Log.w(TAG, "No preference or single system activity found for "
1592 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001593 return -1;
1594 }
Jason Monk41314972014-03-03 16:11:30 -05001595 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001596 }
Jason Monk41314972014-03-03 16:11:30 -05001597 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001598 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001599 intent.setComponent(new ComponentName(info.packageName, info.name));
1600 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1601 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1602
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001603 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001604 }
1605
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001606 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001607 ResolveInfo systemResolve = null;
1608 final int N = appList.size();
1609 for (int i = 0; i < N; ++i) {
1610 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001611 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001612 appList.get(i).activityInfo.packageName, 0);
1613 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1614 if (systemResolve != null) {
1615 return null;
1616 } else {
1617 systemResolve = appList.get(i);
1618 }
1619 }
1620 } catch (PackageManager.NameNotFoundException e) {
1621 Log.w(TAG, "Unable to get info about resolve results", e);
1622 return null;
1623 }
1624 }
1625 return systemResolve;
1626 }
1627
1628 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1629 List<ResolveInfo> appList) {
1630 // If the list contains the above resolved activity, then it can't be
1631 // ResolverActivity itself.
1632 for (int i = 0; i < appList.size(); ++i) {
1633 ResolveInfo tmp = appList.get(i);
1634 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1635 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1636 return false;
1637 }
1638 }
1639 return true;
1640 }
1641
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001642 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1643 XmlResourceParser parser) {
1644 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1645 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1646 final String uri = getAttributeValue(parser, ATTR_URI);
1647
1648 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001649 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001650 try {
1651 ComponentName cn;
1652 try {
1653 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001654 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001655 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001656 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001657 new String[] { packageName });
1658 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001659 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001660 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001661 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001662 intent.setComponent(cn);
1663 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1664 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1665
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001666 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001667 intent);
1668 } catch (PackageManager.NameNotFoundException e) {
1669 Log.w(TAG, "Unable to add favorite: " + packageName +
1670 "/" + className, e);
1671 }
1672 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001673 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001674 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001675 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001676 } else {
1677 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1678 return -1;
1679 }
1680 }
1681
1682 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1683 Intent intent) {
1684 long id = generateNewItemId();
1685 values.put(Favorites.INTENT, intent.toUri(0));
1686 values.put(Favorites.TITLE, title);
1687 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1688 values.put(Favorites.SPANX, 1);
1689 values.put(Favorites.SPANY, 1);
1690 values.put(Favorites._ID, id);
1691 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1692 return -1;
1693 } else {
1694 return id;
1695 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001696 }
1697
1698 private long addFolder(SQLiteDatabase db, ContentValues values) {
1699 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1700 values.put(Favorites.SPANX, 1);
1701 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001702 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001703 values.put(Favorites._ID, id);
1704 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1705 return -1;
1706 } else {
1707 return id;
1708 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001709 }
1710
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001711 private ComponentName getSearchWidgetProvider() {
1712 SearchManager searchManager =
1713 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1714 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1715 if (searchComponent == null) return null;
1716 return getProviderInPackage(searchComponent.getPackageName());
1717 }
1718
1719 /**
1720 * Gets an appwidget provider from the given package. If the package contains more than
1721 * one appwidget provider, an arbitrary one is returned.
1722 */
1723 private ComponentName getProviderInPackage(String packageName) {
1724 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1725 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1726 if (providers == null) return null;
1727 final int providerCount = providers.size();
1728 for (int i = 0; i < providerCount; i++) {
1729 ComponentName provider = providers.get(i).provider;
1730 if (provider != null && provider.getPackageName().equals(packageName)) {
1731 return provider;
1732 }
1733 }
1734 return null;
1735 }
1736
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001737 private boolean addAppWidget(XmlResourceParser parser, int type,
1738 SQLiteDatabase db, ContentValues values)
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001739 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001740
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001741 String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1742 String className = getAttributeValue(parser, ATTR_CLASS_NAME);
Mike Cleronb87bd162009-10-30 16:36:56 -07001743
1744 if (packageName == null || className == null) {
1745 return false;
1746 }
Romain Guy693599f2010-03-23 10:58:18 -07001747
1748 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001749 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001750 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001751 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001752 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001753 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001754 new String[] { packageName });
1755 cn = new ComponentName(packages[0], className);
1756 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001757 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001758 } catch (Exception e1) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001759 System.out.println("Can't find widget provider: " + className);
Romain Guy693599f2010-03-23 10:58:18 -07001760 hasPackage = false;
1761 }
1762 }
1763
1764 if (hasPackage) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001765 String spanX = getAttributeValue(parser, ATTR_SPAN_X);
1766 String spanY = getAttributeValue(parser, ATTR_SPAN_Y);
1767
1768 values.put(Favorites.SPANX, spanX);
1769 values.put(Favorites.SPANY, spanY);
Winson Chungb3302ae2012-05-01 10:19:14 -07001770
1771 // Read the extras
1772 Bundle extras = new Bundle();
1773 int widgetDepth = parser.getDepth();
1774 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1775 parser.getDepth() > widgetDepth) {
1776 if (type != XmlPullParser.START_TAG) {
1777 continue;
1778 }
1779
Winson Chungb3302ae2012-05-01 10:19:14 -07001780 if (TAG_EXTRA.equals(parser.getName())) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001781 String key = getAttributeValue(parser, ATTR_KEY);
1782 String value = getAttributeValue(parser, ATTR_VALUE);
Winson Chungb3302ae2012-05-01 10:19:14 -07001783 if (key != null && value != null) {
1784 extras.putString(key, value);
1785 } else {
1786 throw new RuntimeException("Widget extras must have a key and value");
1787 }
1788 } else {
1789 throw new RuntimeException("Widgets can contain only extras");
1790 }
Winson Chungb3302ae2012-05-01 10:19:14 -07001791 }
1792
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001793 return addAppWidget(db, values, cn, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001794 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001795
Romain Guy693599f2010-03-23 10:58:18 -07001796 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001797 }
Adam Cohena043fa82014-07-23 14:49:38 -07001798
Bjorn Bringert7984c942009-12-09 15:38:25 +00001799 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Adam Cohen9b8f51f2014-05-30 15:34:09 -07001800 Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001801 boolean allocatedAppWidgets = false;
1802 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1803
1804 try {
1805 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001806
Mike Cleronb87bd162009-10-30 16:36:56 -07001807 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Mike Cleronb87bd162009-10-30 16:36:56 -07001808 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001809 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001811 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001812
1813 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001814
Michael Jurka8b805b12012-04-18 14:23:14 -07001815 // TODO: need to check return value
1816 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001817
1818 // Send a broadcast to configure the widget
1819 if (extras != null && !extras.isEmpty()) {
1820 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1821 intent.setComponent(cn);
1822 intent.putExtras(extras);
1823 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1824 mContext.sendBroadcast(intent);
1825 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001826 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001827 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001828 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001829
Mike Cleronb87bd162009-10-30 16:36:56 -07001830 return allocatedAppWidgets;
1831 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001832
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001833 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1834 XmlResourceParser parser) {
1835 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1836 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001837
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001838 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001839 String uri = null;
1840 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001841 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001842 intent = Intent.parseUri(uri, 0);
1843 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001844 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001845 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001846 }
1847
1848 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001849 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001850 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001851 }
1852
Adam Cohendcd297f2013-06-18 13:13:40 -07001853 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001854 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1855 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001856 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001857 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1858 values.put(Favorites.SPANX, 1);
1859 values.put(Favorites.SPANY, 1);
1860 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001861 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1862 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001863 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001864
Adam Cohen228da5a2011-07-27 22:23:47 -07001865 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1866 return -1;
1867 }
1868 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001869 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001870
1871 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1872 final ContentResolver resolver = mContext.getContentResolver();
1873 Cursor c = null;
1874 int count = 0;
1875 int curScreen = 0;
1876
1877 try {
1878 c = resolver.query(uri, null, null, null, "title ASC");
1879 } catch (Exception e) {
1880 // Ignore
1881 }
1882
Dan Sandlerd5024042014-01-09 15:01:33 -05001883 // We already have a favorites database in the old provider
1884 if (c != null) {
1885 try {
1886 if (c.getCount() > 0) {
1887 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1888 final int intentIndex
1889 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1890 final int titleIndex
1891 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1892 final int iconTypeIndex
1893 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1894 final int iconIndex
1895 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1896 final int iconPackageIndex
1897 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1898 final int iconResourceIndex
1899 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1900 final int containerIndex
1901 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1902 final int itemTypeIndex
1903 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1904 final int screenIndex
1905 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1906 final int cellXIndex
1907 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1908 final int cellYIndex
1909 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1910 final int uriIndex
1911 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1912 final int displayModeIndex
1913 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001914 final int profileIndex
1915 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001916
1917 int i = 0;
1918 int curX = 0;
1919 int curY = 0;
1920
1921 final LauncherAppState app = LauncherAppState.getInstance();
1922 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1923 final int width = (int) grid.numColumns;
1924 final int height = (int) grid.numRows;
1925 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001926 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001927
1928 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1929
Adam Cohen72960972014-01-15 18:13:55 -08001930 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1931 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001932 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001933
1934 while (c.moveToNext()) {
1935 final int itemType = c.getInt(itemTypeIndex);
1936 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1937 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1938 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1939 continue;
1940 }
1941
1942 final int cellX = c.getInt(cellXIndex);
1943 final int cellY = c.getInt(cellYIndex);
1944 final int screen = c.getInt(screenIndex);
1945 int container = c.getInt(containerIndex);
1946 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001947
1948 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1949 UserHandleCompat userHandle;
1950 final long userSerialNumber;
1951 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1952 userSerialNumber = c.getInt(profileIndex);
1953 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1954 } else {
1955 // Default to the serial number of this user, for older
1956 // shortcuts.
1957 userHandle = UserHandleCompat.myUserHandle();
1958 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1959 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001960 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001961 + c.getString(titleIndex) + "\" ("
1962 + cellX + "," + cellY + "@"
1963 + LauncherSettings.Favorites.containerToString(container)
1964 + "/" + screen
1965 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001966
1967 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001968
1969 final Intent intent;
1970 final ComponentName cn;
1971 try {
1972 intent = Intent.parseUri(intentStr, 0);
1973 } catch (URISyntaxException e) {
1974 // bogus intent?
1975 Launcher.addDumpLog(TAG,
1976 "skipping invalid intent uri", true);
1977 continue;
1978 }
1979
1980 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001981 if (TextUtils.isEmpty(intentStr)) {
1982 // no intent? no icon
1983 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1984 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001985 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001986 !LauncherModel.isValidPackageActivity(mContext, cn,
1987 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001988 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001989 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001990 "no longer exists.", true);
1991 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001992 } else if (container ==
1993 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1994 // Dedupe icons directly on the workspace
1995
Adam Cohen556f6132014-01-15 15:18:08 -08001996 // Canonicalize
1997 // the Play Store sets the package parameter, but Launcher
1998 // does not, so we clear that out to keep them the same
1999 intent.setPackage(null);
2000 final String key = intent.toUri(0);
2001 if (seenIntents.contains(key)) {
2002 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05002003 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08002004 } else {
2005 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05002006 }
2007 }
2008 }
2009
2010 ContentValues values = new ContentValues(c.getColumnCount());
2011 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
2012 values.put(LauncherSettings.Favorites.INTENT, intentStr);
2013 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
2014 values.put(LauncherSettings.Favorites.ICON_TYPE,
2015 c.getInt(iconTypeIndex));
2016 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
2017 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
2018 c.getString(iconPackageIndex));
2019 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
2020 c.getString(iconResourceIndex));
2021 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
2022 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
2023 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
2024 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
2025 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01002026 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05002027
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002028 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2029 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05002030 }
2031
2032 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2033 // In a folder or in the hotseat, preserve position
2034 values.put(LauncherSettings.Favorites.SCREEN, screen);
2035 values.put(LauncherSettings.Favorites.CELLX, cellX);
2036 values.put(LauncherSettings.Favorites.CELLY, cellY);
2037 } else {
Adam Cohen72960972014-01-15 18:13:55 -08002038 // For items contained directly on one of the workspace screen,
2039 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05002040 }
2041
2042 values.put(LauncherSettings.Favorites.CONTAINER, container);
2043
Adam Cohen72960972014-01-15 18:13:55 -08002044 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
2045 shortcuts.add(values);
2046 } else {
2047 folders.add(values);
2048 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002049 }
2050
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002051 // Now that we have all the hotseat icons, let's go through them left-right
2052 // and assign valid locations for them in the new hotseat
2053 final int N = hotseat.size();
2054 for (int idx=0; idx<N; idx++) {
2055 int hotseatX = hotseat.keyAt(idx);
2056 ContentValues values = hotseat.valueAt(idx);
2057
2058 if (hotseatX == grid.hotseatAllAppsRank) {
2059 // let's drop this in the next available hole in the hotseat
2060 while (++hotseatX < hotseatWidth) {
2061 if (hotseat.get(hotseatX) == null) {
2062 // found a spot! move it here
2063 values.put(LauncherSettings.Favorites.SCREEN,
2064 hotseatX);
2065 break;
2066 }
2067 }
2068 }
2069 if (hotseatX >= hotseatWidth) {
2070 // no room for you in the hotseat? it's off to the desktop with you
2071 values.put(LauncherSettings.Favorites.CONTAINER,
2072 Favorites.CONTAINER_DESKTOP);
2073 }
2074 }
2075
Adam Cohen72960972014-01-15 18:13:55 -08002076 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2077 // Folders first
2078 allItems.addAll(folders);
2079 // Then shortcuts
2080 allItems.addAll(shortcuts);
2081
2082 // Layout all the folders
2083 for (ContentValues values: allItems) {
2084 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2085 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2086 // Hotseat items and folder items have already had their
2087 // location information set. Nothing to be done here.
2088 continue;
2089 }
2090 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2091 values.put(LauncherSettings.Favorites.CELLX, curX);
2092 values.put(LauncherSettings.Favorites.CELLY, curY);
2093 curX = (curX + 1) % width;
2094 if (curX == 0) {
2095 curY = (curY + 1);
2096 }
2097 // Leave the last row of icons blank on every screen
2098 if (curY == height - 1) {
2099 curScreen = (int) generateNewScreenId();
2100 curY = 0;
2101 }
2102 }
2103
2104 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002105 db.beginTransaction();
2106 try {
Adam Cohen72960972014-01-15 18:13:55 -08002107 for (ContentValues row: allItems) {
2108 if (row == null) continue;
2109 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002110 < 0) {
2111 return;
2112 } else {
2113 count++;
2114 }
2115 }
2116 db.setTransactionSuccessful();
2117 } finally {
2118 db.endTransaction();
2119 }
2120 }
2121
2122 db.beginTransaction();
2123 try {
2124 for (i=0; i<=curScreen; i++) {
2125 final ContentValues values = new ContentValues();
2126 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2127 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2128 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2129 < 0) {
2130 return;
2131 }
2132 }
2133 db.setTransactionSuccessful();
2134 } finally {
2135 db.endTransaction();
2136 }
2137 }
2138 } finally {
2139 c.close();
2140 }
2141 }
2142
2143 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2144 + (curScreen+1) + " screens", true);
2145
2146 // ensure that new screens are created to hold these icons
2147 setFlagJustLoadedOldDb();
2148
2149 // Update max IDs; very important since we just grabbed IDs from another database
2150 mMaxItemId = initializeMaxItemId(db);
2151 mMaxScreenId = initializeMaxScreenId(db);
2152 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2153 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002154 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002155
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002156 /**
2157 * Build a query string that will match any row where the column matches
2158 * anything in the values list.
2159 */
2160 static String buildOrWhereString(String column, int[] values) {
2161 StringBuilder selectWhere = new StringBuilder();
2162 for (int i = values.length - 1; i >= 0; i--) {
2163 selectWhere.append(column).append("=").append(values[i]);
2164 if (i > 0) {
2165 selectWhere.append(" OR ");
2166 }
2167 }
2168 return selectWhere.toString();
2169 }
2170
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002171 /**
2172 * Return attribute value, attempting launcher-specific namespace first
2173 * before falling back to anonymous attribute.
2174 */
2175 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2176 String value = parser.getAttributeValue(
2177 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2178 if (value == null) {
2179 value = parser.getAttributeValue(null, attribute);
2180 }
2181 return value;
2182 }
2183
2184 /**
2185 * Return attribute resource value, attempting launcher-specific namespace
2186 * first before falling back to anonymous attribute.
2187 */
2188 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2189 int defaultValue) {
2190 int value = parser.getAttributeResourceValue(
2191 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2192 defaultValue);
2193 if (value == defaultValue) {
2194 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2195 }
2196 return value;
2197 }
2198
2199 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2200 to.put(key, from.getAsInteger(key));
2201 }
2202
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002203 static class SqlArguments {
2204 public final String table;
2205 public final String where;
2206 public final String[] args;
2207
2208 SqlArguments(Uri url, String where, String[] args) {
2209 if (url.getPathSegments().size() == 1) {
2210 this.table = url.getPathSegments().get(0);
2211 this.where = where;
2212 this.args = args;
2213 } else if (url.getPathSegments().size() != 2) {
2214 throw new IllegalArgumentException("Invalid URI: " + url);
2215 } else if (!TextUtils.isEmpty(where)) {
2216 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2217 } else {
2218 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002219 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002220 this.args = null;
2221 }
2222 }
2223
2224 SqlArguments(Uri url) {
2225 if (url.getPathSegments().size() == 1) {
2226 table = url.getPathSegments().get(0);
2227 where = null;
2228 args = null;
2229 } else {
2230 throw new IllegalArgumentException("Invalid URI: " + url);
2231 }
2232 }
2233 }
Adam Cohen72960972014-01-15 18:13:55 -08002234}