blob: 55a0f5e360b20f45220a152fe8015e2ca539cb9b [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
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 private LauncherProviderChangeListener mListener;
103
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700104 /**
Romain Guy73b979d2009-06-09 12:57:21 -0700105 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700106 * {@link AppWidgetHost#deleteHost()} is called during database creation.
107 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
108 */
109 static final Uri CONTENT_APPWIDGET_RESET_URI =
110 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700111
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700112 private DatabaseHelper mOpenHelper;
Winson Chungc763c4e2013-07-19 13:49:06 -0700113 private static boolean sJustLoadedFromOldDb;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114
115 @Override
116 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -0400117 final Context context = getContext();
118 mOpenHelper = new DatabaseHelper(context);
119 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120 return true;
121 }
122
Winson Chung0b560dd2014-01-21 13:00:26 -0800123 public boolean wasNewDbCreated() {
124 return mOpenHelper.wasNewDbCreated();
125 }
126
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700127 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
128 mListener = listener;
129 }
130
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131 @Override
132 public String getType(Uri uri) {
133 SqlArguments args = new SqlArguments(uri, null, null);
134 if (TextUtils.isEmpty(args.where)) {
135 return "vnd.android.cursor.dir/" + args.table;
136 } else {
137 return "vnd.android.cursor.item/" + args.table;
138 }
139 }
140
141 @Override
142 public Cursor query(Uri uri, String[] projection, String selection,
143 String[] selectionArgs, String sortOrder) {
144
145 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
146 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
147 qb.setTables(args.table);
148
Romain Guy73b979d2009-06-09 12:57:21 -0700149 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
151 result.setNotificationUri(getContext().getContentResolver(), uri);
152
153 return result;
154 }
155
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156 private static long dbInsertAndCheck(DatabaseHelper helper,
157 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500158 if (values == null) {
159 throw new RuntimeException("Error: attempting to insert null values");
160 }
Adam Cohen71483f42014-05-15 14:04:01 -0700161 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 throw new RuntimeException("Error: attempting to add item without specifying an id");
163 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500164 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 return db.insert(table, nullColumnHack, values);
166 }
167
Adam Cohen228da5a2011-07-27 22:23:47 -0700168 private static void deleteId(SQLiteDatabase db, long id) {
169 Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
170 SqlArguments args = new SqlArguments(uri, null, null);
171 db.delete(args.table, args.where, args.args);
172 }
173
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 @Override
175 public Uri insert(Uri uri, ContentValues initialValues) {
176 SqlArguments args = new SqlArguments(uri);
177
178 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400179 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700180 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 if (rowId <= 0) return null;
182
183 uri = ContentUris.withAppendedId(uri, rowId);
184 sendNotify(uri);
185
186 return uri;
187 }
188
189 @Override
190 public int bulkInsert(Uri uri, ContentValues[] values) {
191 SqlArguments args = new SqlArguments(uri);
192
193 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
194 db.beginTransaction();
195 try {
196 int numValues = values.length;
197 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400198 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700199 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
200 return 0;
201 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 }
203 db.setTransactionSuccessful();
204 } finally {
205 db.endTransaction();
206 }
207
208 sendNotify(uri);
209 return values.length;
210 }
211
212 @Override
Yura085c8532014-02-11 15:15:29 +0000213 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
214 throws OperationApplicationException {
215 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
216 db.beginTransaction();
217 try {
218 ContentProviderResult[] result = super.applyBatch(operations);
219 db.setTransactionSuccessful();
220 return result;
221 } finally {
222 db.endTransaction();
223 }
224 }
225
226 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227 public int delete(Uri uri, String selection, String[] selectionArgs) {
228 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
229
230 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
231 int count = db.delete(args.table, args.where, args.args);
232 if (count > 0) sendNotify(uri);
233
234 return count;
235 }
236
237 @Override
238 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
239 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
240
Chris Wren1ada10d2013-09-13 18:01:38 -0400241 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
243 int count = db.update(args.table, values, args.where, args.args);
244 if (count > 0) sendNotify(uri);
245
246 return count;
247 }
248
249 private void sendNotify(Uri uri) {
250 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
251 if (notify == null || "true".equals(notify)) {
252 getContext().getContentResolver().notifyChange(uri, null);
253 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400254
255 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400256 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700257 if (mListener != null) {
258 mListener.onLauncherProviderChange();
259 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400260 }
261
262 private void addModifiedTime(ContentValues values) {
263 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 }
265
Adam Cohendcd297f2013-06-18 13:13:40 -0700266 public long generateNewItemId() {
267 return mOpenHelper.generateNewItemId();
268 }
269
Winson Chungc763c4e2013-07-19 13:49:06 -0700270 public void updateMaxItemId(long id) {
271 mOpenHelper.updateMaxItemId(id);
272 }
273
Adam Cohendcd297f2013-06-18 13:13:40 -0700274 public long generateNewScreenId() {
275 return mOpenHelper.generateNewScreenId();
276 }
277
278 // This is only required one time while loading the workspace during the
279 // upgrade path, and should never be called from anywhere else.
280 public void updateMaxScreenId(long maxScreenId) {
281 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700282 }
283
Brian Muramatsu5524b492012-10-02 16:55:54 -0700284 /**
Adam Cohene25af792013-06-06 23:08:25 -0700285 * @param Should we load the old db for upgrade? first run only.
286 */
Winson Chungc763c4e2013-07-19 13:49:06 -0700287 synchronized public boolean justLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400288 String spKey = LauncherAppState.getSharedPreferencesKey();
Adam Cohene25af792013-06-06 23:08:25 -0700289 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
290
Winson Chungc763c4e2013-07-19 13:49:06 -0700291 boolean loadedOldDb = false || sJustLoadedFromOldDb;
Adam Cohendcd297f2013-06-18 13:13:40 -0700292
Winson Chungc763c4e2013-07-19 13:49:06 -0700293 sJustLoadedFromOldDb = false;
294 if (sp.getBoolean(UPGRADED_FROM_OLD_DATABASE, false)) {
Adam Cohene25af792013-06-06 23:08:25 -0700295
296 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700297 editor.remove(UPGRADED_FROM_OLD_DATABASE);
Adam Cohene25af792013-06-06 23:08:25 -0700298 editor.commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700299 loadedOldDb = true;
Adam Cohene25af792013-06-06 23:08:25 -0700300 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700301 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -0700302 }
303
304 /**
Brian Muramatsu5524b492012-10-02 16:55:54 -0700305 * @param workspaceResId that can be 0 to use default or non-zero for specific resource
306 */
Michael Jurka45355c42012-10-08 13:21:35 +0200307 synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400308 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700309 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700310
Winson Chungc763c4e2013-07-19 13:49:06 -0700311 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500312 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200313 int workspaceResId = origWorkspaceResId;
314
Brian Muramatsu5524b492012-10-02 16:55:54 -0700315 // Use default workspace resource if none provided
316 if (workspaceResId == 0) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800317 workspaceResId =
318 sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, getDefaultWorkspaceResourceId());
Brian Muramatsu5524b492012-10-02 16:55:54 -0700319 }
320
Michael Jurkab85f8a42012-04-25 15:48:32 -0700321 // Populate favorites table with initial favorites
322 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700323 editor.remove(EMPTY_DATABASE_CREATED);
Michael Jurka45355c42012-10-08 13:21:35 +0200324 if (origWorkspaceResId != 0) {
325 editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
326 }
Adam Cohene25af792013-06-06 23:08:25 -0700327
Brian Muramatsu5524b492012-10-02 16:55:54 -0700328 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700329 editor.commit();
330 }
331 }
332
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 public void migrateLauncher2Shortcuts() {
334 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400335 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 }
337
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800338 private static int getDefaultWorkspaceResourceId() {
Winson Chungbe876472014-05-14 14:15:20 -0700339 LauncherAppState app = LauncherAppState.getInstance();
340 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800341 if (LauncherAppState.isDisableAllApps()) {
Winson Chungbe876472014-05-14 14:15:20 -0700342 return grid.defaultNoAllAppsLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800343 } else {
Winson Chungbe876472014-05-14 14:15:20 -0700344 return grid.defaultLayoutId;
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800345 }
346 }
347
Winson Chungc763c4e2013-07-19 13:49:06 -0700348 private static interface ContentValuesCallback {
349 public void onRow(ContentValues values);
350 }
351
Adam Cohen6dbe0492013-12-02 17:00:14 -0800352 private static boolean shouldImportLauncher2Database(Context context) {
353 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
354
355 // We don't import the old databse for tablets, as the grid size has changed.
356 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
357 }
358
Dan Sandlerd5024042014-01-09 15:01:33 -0500359 public void deleteDatabase() {
360 // Are you sure? (y/n)
361 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500362 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500363 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500364 if (dbFile.exists()) {
365 SQLiteDatabase.deleteDatabase(dbFile);
366 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500367 mOpenHelper = new DatabaseHelper(getContext());
368 }
369
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800370 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500371 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800372 private static final String TAG_FAVORITES = "favorites";
373 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700374 private static final String TAG_CLOCK = "clock";
375 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700376 private static final String TAG_APPWIDGET = "appwidget";
377 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700378 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700379 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700380 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400381 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700382
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700383 private static final String ATTR_TITLE = "title";
384 private static final String ATTR_ICON = "icon";
385 private static final String ATTR_URI = "uri";
386 private static final String ATTR_PACKAGE_NAME = "packageName";
387 private static final String ATTR_CLASS_NAME = "className";
388
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700390 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700391 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700392 private long mMaxItemId = -1;
393 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394
Winson Chung0b560dd2014-01-21 13:00:26 -0800395 private boolean mNewDbCreated = false;
396
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 DatabaseHelper(Context context) {
398 super(context, DATABASE_NAME, null, DATABASE_VERSION);
399 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700400 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700401 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700402
403 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
404 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700405 if (mMaxItemId == -1) {
406 mMaxItemId = initializeMaxItemId(getWritableDatabase());
407 }
408 if (mMaxScreenId == -1) {
409 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700410 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800411 }
412
Winson Chung0b560dd2014-01-21 13:00:26 -0800413 public boolean wasNewDbCreated() {
414 return mNewDbCreated;
415 }
416
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700417 /**
418 * Send notification that we've deleted the {@link AppWidgetHost},
419 * probably as part of the initial database creation. The receiver may
420 * want to re-call {@link AppWidgetHost#startListening()} to ensure
421 * callbacks are correctly set.
422 */
423 private void sendAppWidgetResetNotify() {
424 final ContentResolver resolver = mContext.getContentResolver();
425 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
426 }
427
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800428 @Override
429 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800430 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700431
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 mMaxItemId = 1;
433 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800434 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700435
Kenny Guyed131872014-04-30 03:02:21 +0100436 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
437 long userSerialNumber = userManager.getSerialNumberForUser(
438 UserHandleCompat.myUserHandle());
439
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800440 db.execSQL("CREATE TABLE favorites (" +
441 "_id INTEGER PRIMARY KEY," +
442 "title TEXT," +
443 "intent TEXT," +
444 "container INTEGER," +
445 "screen INTEGER," +
446 "cellX INTEGER," +
447 "cellY INTEGER," +
448 "spanX INTEGER," +
449 "spanY INTEGER," +
450 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700451 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800452 "isShortcut INTEGER," +
453 "iconType INTEGER," +
454 "iconPackage TEXT," +
455 "iconResource TEXT," +
456 "icon BLOB," +
457 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400458 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400459 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500460 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100461 "restored INTEGER NOT NULL DEFAULT 0," +
462 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700464 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700466 // Database was just created, so wipe any previous widgets
467 if (mAppWidgetHost != null) {
468 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700469 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800470 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700471
Adam Cohen6dbe0492013-12-02 17:00:14 -0800472 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500473 // Try converting the old database
474 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
475 public void onRow(ContentValues values) {
476 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
477 if (container == Favorites.CONTAINER_DESKTOP) {
478 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
479 screen = (int) upgradeLauncherDb_permuteScreens(screen);
480 values.put(LauncherSettings.Favorites.SCREEN, screen);
481 }
482 }
483 };
484 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
485 "/old_favorites?notify=true");
486 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
487 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400488 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500489 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
490 // If we fail, then set a flag to load the default workspace
491 setFlagEmptyDbCreated();
492 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700493 }
494 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500495 // Right now, in non-default workspace cases, we want to run the final
496 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
497 // set that flag too.
498 setFlagJustLoadedOldDb();
499 } else {
500 // Fresh and clean launcher DB.
501 mMaxItemId = initializeMaxItemId(db);
502 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800503 }
504 }
505
Adam Cohendcd297f2013-06-18 13:13:40 -0700506 private void addWorkspacesTable(SQLiteDatabase db) {
507 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
508 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400509 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
510 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700511 ");");
512 }
513
Adam Cohen119285e2014-04-02 16:59:08 -0700514 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700515 // Delete items directly on the workspace who's screen id doesn't exist
516 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
517 // AND container = -100"
518 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
519 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700520 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700521 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
522 " AND " +
523 LauncherSettings.Favorites.CONTAINER + " = " +
524 LauncherSettings.Favorites.CONTAINER_DESKTOP;
525 db.execSQL(removeOrphanedDesktopItems);
526
527 // Delete items contained in folders which no longer exist (after above statement)
528 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
529 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
530 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
531 " WHERE " +
532 LauncherSettings.Favorites.CONTAINER + " <> " +
533 LauncherSettings.Favorites.CONTAINER_DESKTOP +
534 " AND "
535 + LauncherSettings.Favorites.CONTAINER + " <> " +
536 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
537 " AND "
538 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
539 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
540 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
541 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
542 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700543 }
544
Winson Chungc763c4e2013-07-19 13:49:06 -0700545 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400546 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700547 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
548 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700549 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
550 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700551 editor.commit();
552 }
553
Winson Chungc763c4e2013-07-19 13:49:06 -0700554 private void setFlagEmptyDbCreated() {
555 String spKey = LauncherAppState.getSharedPreferencesKey();
556 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
557 SharedPreferences.Editor editor = sp.edit();
558 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
559 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
560 editor.commit();
561 }
562
563 // We rearrange the screens from the old launcher
564 // 12345 -> 34512
565 private long upgradeLauncherDb_permuteScreens(long screen) {
566 if (screen >= 2) {
567 return screen - 2;
568 } else {
569 return screen + 3;
570 }
571 }
572
573 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
574 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800575 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 boolean converted = false;
577
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800578 final ContentResolver resolver = mContext.getContentResolver();
579 Cursor cursor = null;
580
581 try {
582 cursor = resolver.query(uri, null, null, null, null);
583 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700584 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 }
586
587 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700588 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700590 if (cursor.getCount() > 0) {
591 converted = copyFromCursor(db, cursor, cb) > 0;
592 if (converted && deleteRows) {
593 resolver.delete(uri, null, null);
594 }
595 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 } finally {
597 cursor.close();
598 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700600
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700602 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800603 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800604 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700605
606 // Update max item id
607 mMaxItemId = initializeMaxItemId(db);
608 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609 }
610
611 return converted;
612 }
613
Winson Chungc763c4e2013-07-19 13:49:06 -0700614 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700615 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
617 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
618 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
619 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
620 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
621 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
622 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
623 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
624 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
625 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
626 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
627 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
628 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
629
630 ContentValues[] rows = new ContentValues[c.getCount()];
631 int i = 0;
632 while (c.moveToNext()) {
633 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700634 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
636 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
637 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
638 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
639 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
640 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
641 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
642 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700643 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800644 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
645 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
646 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
647 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
648 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700649 if (cb != null) {
650 cb.onRow(values);
651 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652 rows[i++] = values;
653 }
654
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800655 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700656 if (i > 0) {
657 db.beginTransaction();
658 try {
659 int numValues = rows.length;
660 for (i = 0; i < numValues; i++) {
661 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
662 return 0;
663 } else {
664 total++;
665 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800666 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700667 db.setTransactionSuccessful();
668 } finally {
669 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800671 }
672
673 return total;
674 }
675
676 @Override
677 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700678 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700679
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800680 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700681 if (version < 3) {
682 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800683 db.beginTransaction();
684 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700685 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700687 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700689 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800690 } catch (SQLException ex) {
691 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800692 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800693 } finally {
694 db.endTransaction();
695 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700696
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700698 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 convertWidgets(db);
700 }
701 }
Romain Guy73b979d2009-06-09 12:57:21 -0700702
703 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800704 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700705 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700706
Romain Guy509cd6a2010-03-23 15:10:56 -0700707 // Where's version 5?
708 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400709 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700710 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
711 // but version 5 on there was the updateContactsShortcuts change
712 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
713 // The updateContactsShortcuts change is idempotent, so running it twice
714 // is okay so we'll do that when upgrading the devices that shipped with it.
715 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800716 // We went from 3 to 5 screens. Move everything 1 to the right
717 db.beginTransaction();
718 try {
719 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
720 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800721 } catch (SQLException ex) {
722 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800723 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800724 } finally {
725 db.endTransaction();
726 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700727
Romain Guy509cd6a2010-03-23 15:10:56 -0700728 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800729 if (updateContactsShortcuts(db)) {
730 version = 6;
731 }
732 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000733
734 if (version < 7) {
735 // Version 7 gets rid of the special search widget.
736 convertWidgets(db);
737 version = 7;
738 }
739
Joe Onorato0589f0f2010-02-08 13:44:00 -0800740 if (version < 8) {
741 // Version 8 (froyo) has the icons all normalized. This should
742 // already be the case in practice, but we now rely on it and don't
743 // resample the images each time.
744 normalizeIcons(db);
745 version = 8;
746 }
747
Winson Chung3d503fb2011-07-13 17:25:49 -0700748 if (version < 9) {
749 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
750 // before it gets a change to get set, so we need to read it here when we use it)
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 if (mMaxItemId == -1) {
752 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700753 }
754
755 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800756 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700757 version = 9;
758 }
759
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700760 // We bumped the version three time during JB, once to update the launch flags, once to
761 // update the override for the default launch animation and once to set the mimetype
762 // to improve startup performance
763 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700764 // Contact shortcuts need a different set of flags to be launched now
765 // The updateContactsShortcuts change is idempotent, so we can keep using it like
766 // back in the Donut days
767 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700768 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700769 }
770
Adam Cohendcd297f2013-06-18 13:13:40 -0700771 if (version < 13) {
772 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
773 // to persist workspace screens and their relative order.
774 mMaxScreenId = 0;
775
776 // This will never happen in the wild, but when we switch to using workspace
777 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700778 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700779
780 addWorkspacesTable(db);
781 version = 13;
782 }
783
Chris Wrend5e66bf2013-09-16 14:02:29 -0400784 if (version < 14) {
785 db.beginTransaction();
786 try {
787 // Insert new column for holding widget provider name
788 db.execSQL("ALTER TABLE favorites " +
789 "ADD COLUMN appWidgetProvider TEXT;");
790 db.setTransactionSuccessful();
791 version = 14;
792 } catch (SQLException ex) {
793 // Old version remains, which means we wipe old data
794 Log.e(TAG, ex.getMessage(), ex);
795 } finally {
796 db.endTransaction();
797 }
798 }
799
Chris Wren1ada10d2013-09-13 18:01:38 -0400800 if (version < 15) {
801 db.beginTransaction();
802 try {
803 // Insert new column for holding update timestamp
804 db.execSQL("ALTER TABLE favorites " +
805 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
806 db.execSQL("ALTER TABLE workspaceScreens " +
807 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
808 db.setTransactionSuccessful();
809 version = 15;
810 } catch (SQLException ex) {
811 // Old version remains, which means we wipe old data
812 Log.e(TAG, ex.getMessage(), ex);
813 } finally {
814 db.endTransaction();
815 }
816 }
817
Chris Wrenf4d08112014-01-16 18:13:56 -0500818
819 if (version < 16) {
820 db.beginTransaction();
821 try {
822 // Insert new column for holding restore status
823 db.execSQL("ALTER TABLE favorites " +
824 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
825 db.setTransactionSuccessful();
826 version = 16;
827 } catch (SQLException ex) {
828 // Old version remains, which means we wipe old data
829 Log.e(TAG, ex.getMessage(), ex);
830 } finally {
831 db.endTransaction();
832 }
833 }
834
Adam Cohen71e03b92014-02-21 14:09:53 -0800835 if (version < 17) {
836 // We use the db version upgrade here to identify users who may not have seen
837 // clings yet (because they weren't available), but for whom the clings are now
838 // available (tablet users). Because one of the possible cling flows (migration)
839 // is very destructive (wipes out workspaces), we want to prevent this from showing
840 // until clear data. We do so by marking that the clings have been shown.
841 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
842 version = 17;
843 }
844
Adam Cohen119285e2014-04-02 16:59:08 -0700845 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700846 // No-op
847 version = 18;
848 }
849
850 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700851 // Due to a data loss bug, some users may have items associated with screen ids
852 // which no longer exist. Since this can cause other problems, and since the user
853 // will never see these items anyway, we use database upgrade as an opportunity to
854 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700855 removeOrphanedItems(db);
856 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700857 }
858
Kenny Guyed131872014-04-30 03:02:21 +0100859 if (version < 20) {
860 // Add userId column
861 if (addProfileColumn(db)) {
862 version = 20;
863 }
864 // else old version remains, which means we wipe old data
865 }
866
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800868 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800869 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700870 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
871
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872 onCreate(db);
873 }
874 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800875
Kenny Guyed131872014-04-30 03:02:21 +0100876 private boolean addProfileColumn(SQLiteDatabase db) {
877 db.beginTransaction();
878 try {
879 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
880 // Default to the serial number of this user, for older
881 // shortcuts.
882 long userSerialNumber = userManager.getSerialNumberForUser(
883 UserHandleCompat.myUserHandle());
884 // Insert new column for holding user serial number
885 db.execSQL("ALTER TABLE favorites " +
886 "ADD COLUMN profileId INTEGER DEFAULT "
887 + userSerialNumber + ";");
888 db.setTransactionSuccessful();
889 } catch (SQLException ex) {
890 // Old version remains, which means we wipe old data
891 Log.e(TAG, ex.getMessage(), ex);
892 return false;
893 } finally {
894 db.endTransaction();
895 }
896 return true;
897 }
898
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800899 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800900 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
901 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
902
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700903 Cursor c = null;
904 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800905 db.beginTransaction();
906 try {
907 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700908 c = db.query(TABLE_FAVORITES,
909 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800910 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700911 if (c == null) return false;
912
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800913 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700914
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800915 final int idIndex = c.getColumnIndex(Favorites._ID);
916 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700917
918 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800919 long favoriteId = c.getLong(idIndex);
920 final String intentUri = c.getString(intentIndex);
921 if (intentUri != null) {
922 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700923 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800924 android.util.Log.d("Home", intent.toString());
925 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700926 if (uri != null) {
927 final String data = uri.toString();
928 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
929 actionQuickContact.equals(intent.getAction())) &&
930 (data.startsWith("content://contacts/people/") ||
931 data.startsWith("content://com.android.contacts/" +
932 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800933
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700934 final Intent newIntent = new Intent(actionQuickContact);
935 // When starting from the launcher, start in a new, cleared task
936 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
937 // clear the whole thing preemptively here since
938 // QuickContactActivity will finish itself when launching other
939 // detail activities.
940 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
941 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700942 newIntent.putExtra(
943 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700944 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700945 // Determine the type and also put that in the shortcut
946 // (that can speed up launch a bit)
947 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800948
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700949 final ContentValues values = new ContentValues();
950 values.put(LauncherSettings.Favorites.INTENT,
951 newIntent.toUri(0));
952
953 String updateWhere = Favorites._ID + "=" + favoriteId;
954 db.update(TABLE_FAVORITES, values, updateWhere, null);
955 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800956 }
957 } catch (RuntimeException ex) {
958 Log.e(TAG, "Problem upgrading shortcut", ex);
959 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700960 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800961 }
962 }
963 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700964
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800965 db.setTransactionSuccessful();
966 } catch (SQLException ex) {
967 Log.w(TAG, "Problem while upgrading contacts", ex);
968 return false;
969 } finally {
970 db.endTransaction();
971 if (c != null) {
972 c.close();
973 }
974 }
975
976 return true;
977 }
978
Joe Onorato0589f0f2010-02-08 13:44:00 -0800979 private void normalizeIcons(SQLiteDatabase db) {
980 Log.d(TAG, "normalizing icons");
981
Joe Onorato346e1292010-02-18 10:34:24 -0500982 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800983 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400984 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800985 try {
986 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400987 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600988 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800989
990 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
991 Favorites.ICON_TYPE_BITMAP, null);
992
993 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
994 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
995
996 while (c.moveToNext()) {
997 long id = c.getLong(idIndex);
998 byte[] data = c.getBlob(iconIndex);
999 try {
1000 Bitmap bitmap = Utilities.resampleIconBitmap(
1001 BitmapFactory.decodeByteArray(data, 0, data.length),
1002 mContext);
1003 if (bitmap != null) {
1004 update.bindLong(1, id);
1005 data = ItemInfo.flattenBitmap(bitmap);
1006 if (data != null) {
1007 update.bindBlob(2, data);
1008 update.execute();
1009 }
1010 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001011 }
1012 } catch (Exception e) {
1013 if (!logged) {
1014 Log.e(TAG, "Failed normalizing icon " + id, e);
1015 } else {
1016 Log.e(TAG, "Also failed normalizing icon " + id);
1017 }
1018 logged = true;
1019 }
1020 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001021 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001022 } catch (SQLException ex) {
1023 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1024 } finally {
1025 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001026 if (update != null) {
1027 update.close();
1028 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001029 if (c != null) {
1030 c.close();
1031 }
1032 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001033 }
1034
1035 // Generates a new ID to use for an object in your database. This method should be only
1036 // called from the main UI thread. As an exception, we do call it when we call the
1037 // constructor from the worker thread; however, this doesn't extend until after the
1038 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1039 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001040 public long generateNewItemId() {
1041 if (mMaxItemId < 0) {
1042 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001043 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001044 mMaxItemId += 1;
1045 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001046 }
1047
Winson Chungc763c4e2013-07-19 13:49:06 -07001048 public void updateMaxItemId(long id) {
1049 mMaxItemId = id + 1;
1050 }
1051
Chris Wren5dee7af2013-12-20 17:22:11 -05001052 public void checkId(String table, ContentValues values) {
1053 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1054 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1055 mMaxScreenId = Math.max(id, mMaxScreenId);
1056 } else {
1057 mMaxItemId = Math.max(id, mMaxItemId);
1058 }
1059 }
1060
Adam Cohendcd297f2013-06-18 13:13:40 -07001061 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001062 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1063
1064 // get the result
1065 final int maxIdIndex = 0;
1066 long id = -1;
1067 if (c != null && c.moveToNext()) {
1068 id = c.getLong(maxIdIndex);
1069 }
Michael Jurka5130e402011-10-13 04:55:35 -07001070 if (c != null) {
1071 c.close();
1072 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001073
1074 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 throw new RuntimeException("Error: could not query max item id");
1076 }
1077
1078 return id;
1079 }
1080
1081 // Generates a new ID to use for an workspace screen in your database. This method
1082 // should be only called from the main UI thread. As an exception, we do call it when we
1083 // call the constructor from the worker thread; however, this doesn't extend until after the
1084 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1085 // after that point
1086 public long generateNewScreenId() {
1087 if (mMaxScreenId < 0) {
1088 throw new RuntimeException("Error: max screen id was not initialized");
1089 }
1090 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001091 // Log to disk
1092 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001093 return mMaxScreenId;
1094 }
1095
1096 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001097 // Log to disk
1098 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001099 mMaxScreenId = maxScreenId;
1100 }
1101
1102 private long initializeMaxScreenId(SQLiteDatabase db) {
1103 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1104
1105 // get the result
1106 final int maxIdIndex = 0;
1107 long id = -1;
1108 if (c != null && c.moveToNext()) {
1109 id = c.getLong(maxIdIndex);
1110 }
1111 if (c != null) {
1112 c.close();
1113 }
1114
1115 if (id == -1) {
1116 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001117 }
1118
Winson Chunga90303b2013-11-15 13:05:06 -08001119 // Log to disk
1120 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001121 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001122 }
1123
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001124 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001125 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001126 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001127 */
1128 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001129 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001130 final int[] bindSources = new int[] {
1131 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1132 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001133 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001135
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001139
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001140 db.beginTransaction();
1141 try {
1142 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001143 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001144 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001145
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001146 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001147
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 final ContentValues values = new ContentValues();
1149 while (c != null && c.moveToNext()) {
1150 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001151 int favoriteType = c.getInt(1);
1152
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001153 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001155 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001156
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001157 if (LOGD) {
1158 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1159 + " for favoriteId=" + favoriteId);
1160 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001161 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001162 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1163 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1164
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001165 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001166 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1167 values.put(LauncherSettings.Favorites.SPANX, 4);
1168 values.put(LauncherSettings.Favorites.SPANY, 1);
1169 } else {
1170 values.put(LauncherSettings.Favorites.SPANX, 2);
1171 values.put(LauncherSettings.Favorites.SPANY, 2);
1172 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001173
1174 String updateWhere = Favorites._ID + "=" + favoriteId;
1175 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001176
Bjorn Bringert34251342009-12-15 13:33:11 +00001177 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001178 // TODO: check return value
1179 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001180 new ComponentName("com.android.alarmclock",
1181 "com.android.alarmclock.AnalogAppWidgetProvider"));
1182 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001183 // TODO: check return value
1184 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001185 new ComponentName("com.android.camera",
1186 "com.android.camera.PhotoAppWidgetProvider"));
1187 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001188 // TODO: check return value
1189 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001190 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001191 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001192 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001193 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001194 }
1195 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001196
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001197 db.setTransactionSuccessful();
1198 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001199 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001200 } finally {
1201 db.endTransaction();
1202 if (c != null) {
1203 c.close();
1204 }
1205 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001206
1207 // Update max item id
1208 mMaxItemId = initializeMaxItemId(db);
1209 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001210 }
1211
Michael Jurka8b805b12012-04-18 14:23:14 -07001212 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1213 throws XmlPullParserException, IOException {
1214 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001215 while ((type = parser.next()) != XmlPullParser.START_TAG
1216 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001217 ;
1218 }
1219
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001220 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001221 throw new XmlPullParserException("No start tag found");
1222 }
1223
1224 if (!parser.getName().equals(firstElementName)) {
1225 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1226 ", expected " + firstElementName);
1227 }
1228 }
1229
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001230 private static Intent buildMainIntent() {
1231 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1232 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1233 return intent;
1234 }
1235
Adam Cohen71483f42014-05-15 14:04:01 -07001236 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
1237 ArrayList<Long> screenIds = new ArrayList<Long>();
1238 int count = loadFavoritesRecursive(db, workspaceResourceId, screenIds);
1239
1240 // Add the screens specified by the items above
1241 Collections.sort(screenIds);
1242 int rank = 0;
1243 ContentValues values = new ContentValues();
1244 for (Long id : screenIds) {
1245 values.clear();
1246 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1247 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1248 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1249 throw new RuntimeException("Failed initialize screen table"
1250 + "from default layout");
1251 }
1252 rank++;
1253 }
1254
1255 // Ensure that the max ids are initialized
1256 mMaxItemId = initializeMaxItemId(db);
1257 mMaxScreenId = initializeMaxScreenId(db);
1258 return count;
1259 }
1260
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001261 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001262 * Loads the default set of favorite packages from an xml file.
1263 *
1264 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001265 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001266 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001267 */
Adam Cohen71483f42014-05-15 14:04:01 -07001268 private int loadFavoritesRecursive(SQLiteDatabase db, int workspaceResourceId,
1269 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001270
Adam Cohen71483f42014-05-15 14:04:01 -07001271
1272
1273 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001274 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1275
Adam Cohen71483f42014-05-15 14:04:01 -07001276 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001277 try {
Winson Chung6d092682011-11-16 18:43:26 -08001278 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001279 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001280 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001281
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001282 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001283
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001284 int type;
1285 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1286 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1287
1288 if (type != XmlPullParser.START_TAG) {
1289 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001290 }
1291
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001292 boolean added = false;
1293 final String name = parser.getName();
1294
Daniel Sandler57dac262013-10-03 13:28:36 -04001295 if (TAG_INCLUDE.equals(name)) {
1296 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1297
1298 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1299
1300 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1301 "", resId));
1302
1303 if (resId != 0 && resId != workspaceResourceId) {
1304 // recursively load some more favorites, why not?
Adam Cohen71483f42014-05-15 14:04:01 -07001305 count += loadFavoritesRecursive(db, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001306 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001307 } else {
1308 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1309 }
1310
1311 a.recycle();
1312
1313 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1314 continue;
1315 }
1316
1317 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001318 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1319
Winson Chung3d503fb2011-07-13 17:25:49 -07001320 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1321 if (a.hasValue(R.styleable.Favorite_container)) {
1322 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1323 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001324
Winson Chung6d092682011-11-16 18:43:26 -08001325 String screen = a.getString(R.styleable.Favorite_screen);
1326 String x = a.getString(R.styleable.Favorite_x);
1327 String y = a.getString(R.styleable.Favorite_y);
1328
Winson Chung6d092682011-11-16 18:43:26 -08001329 values.clear();
1330 values.put(LauncherSettings.Favorites.CONTAINER, container);
1331 values.put(LauncherSettings.Favorites.SCREEN, screen);
1332 values.put(LauncherSettings.Favorites.CELLX, x);
1333 values.put(LauncherSettings.Favorites.CELLY, y);
1334
Daniel Sandler57dac262013-10-03 13:28:36 -04001335 if (LOGD) {
1336 final String title = a.getString(R.styleable.Favorite_title);
1337 final String pkg = a.getString(R.styleable.Favorite_packageName);
1338 final String something = title != null ? title : pkg;
1339 Log.v(TAG, String.format(
1340 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1341 "", name,
1342 (something == null ? "" : (" \"" + something + "\"")),
1343 container, screen, x, y));
1344 }
1345
Winson Chung6d092682011-11-16 18:43:26 -08001346 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001347 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001348 added = id >= 0;
1349 } else if (TAG_SEARCH.equals(name)) {
1350 added = addSearchWidget(db, values);
1351 } else if (TAG_CLOCK.equals(name)) {
1352 added = addClockWidget(db, values);
1353 } else if (TAG_APPWIDGET.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001354 added = addAppWidget(parser, attrs, type, db, values, a);
Winson Chung6d092682011-11-16 18:43:26 -08001355 } else if (TAG_SHORTCUT.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001356 long id = addUriShortcut(db, values, mContext.getResources(), parser);
Winson Chung6d092682011-11-16 18:43:26 -08001357 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001358 } else if (TAG_RESOLVE.equals(name)) {
1359 // This looks through the contained favorites (or meta-favorites) and
1360 // attempts to add them as shortcuts in the fallback group's location
1361 // until one is added successfully.
1362 added = false;
1363 final int groupDepth = parser.getDepth();
1364 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1365 parser.getDepth() > groupDepth) {
1366 if (type != XmlPullParser.START_TAG) {
1367 continue;
1368 }
1369 final String fallback_item_name = parser.getName();
1370 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1371 R.styleable.Favorite);
1372 if (!added) {
1373 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001374 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001375 added = id >= 0;
1376 } else {
1377 Log.e(TAG, "Fallback groups can contain only favorites "
1378 + ar.toString());
1379 }
1380 }
1381 ar.recycle();
1382 }
Winson Chung6d092682011-11-16 18:43:26 -08001383 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001384 // Folder contents are nested in this XML file
1385 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001386
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001387 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1388 // Folder contents come from an external XML resource
1389 final Partner partner = Partner.get(mPackageManager);
1390 if (partner != null) {
1391 final Resources partnerRes = partner.getResources();
1392 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1393 "xml", partner.getPackageName());
1394 if (resId != 0) {
1395 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1396 beginDocument(partnerParser, TAG_FOLDER);
1397 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001398 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001399 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001400 }
Adam Cohen71483f42014-05-15 14:04:01 -07001401 if (added) {
1402 long screenId = Long.parseLong(screen);
1403 // Keep track of the set of screens which need to be added to the db.
1404 if (!screenIds.contains(screenId) &&
1405 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1406 screenIds.add(screenId);
1407 }
1408 count++;
1409 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001410 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001411 }
1412 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001413 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001414 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001415 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001416 } catch (RuntimeException e) {
1417 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001418 }
Adam Cohen71483f42014-05-15 14:04:01 -07001419 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001420 }
1421
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001422 /**
1423 * Parse folder starting at current {@link XmlPullParser} location.
1424 */
1425 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1426 XmlResourceParser parser) throws IOException, XmlPullParserException {
1427 final String title;
1428 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1429 if (titleResId != 0) {
1430 title = res.getString(titleResId);
1431 } else {
1432 title = mContext.getResources().getString(R.string.folder_name);
1433 }
1434
1435 values.put(LauncherSettings.Favorites.TITLE, title);
1436 long folderId = addFolder(db, values);
1437 boolean added = folderId >= 0;
1438
1439 ArrayList<Long> folderItems = new ArrayList<Long>();
1440
1441 int type;
1442 int folderDepth = parser.getDepth();
1443 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1444 parser.getDepth() > folderDepth) {
1445 if (type != XmlPullParser.START_TAG) {
1446 continue;
1447 }
1448 final String tag = parser.getName();
1449
1450 final ContentValues childValues = new ContentValues();
1451 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1452
1453 if (LOGD) {
1454 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1455 final String uri = getAttributeValue(parser, ATTR_URI);
1456 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1457 tag, uri != null ? uri : pkg));
1458 }
1459
1460 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1461 final long id = addAppShortcut(db, childValues, parser);
1462 if (id >= 0) {
1463 folderItems.add(id);
1464 }
1465 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1466 final long id = addUriShortcut(db, childValues, res, parser);
1467 if (id >= 0) {
1468 folderItems.add(id);
1469 }
1470 } else {
1471 throw new RuntimeException("Folders can contain only shortcuts");
1472 }
1473 }
1474
1475 // We can only have folders with >= 2 items, so we need to remove the
1476 // folder and clean up if less than 2 items were included, or some
1477 // failed to add, and less than 2 were actually added
1478 if (folderItems.size() < 2 && folderId >= 0) {
1479 // Delete the folder
1480 deleteId(db, folderId);
1481
1482 // If we have a single item, promote it to where the folder
1483 // would have been.
1484 if (folderItems.size() == 1) {
1485 final ContentValues childValues = new ContentValues();
1486 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1487 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1488 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1489 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1490
1491 final long id = folderItems.get(0);
1492 db.update(TABLE_FAVORITES, childValues,
1493 LauncherSettings.Favorites._ID + "=" + id, null);
1494 } else {
1495 added = false;
1496 }
1497 }
1498 return added;
1499 }
1500
Jason Monk41314972014-03-03 16:11:30 -05001501 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1502 // logical choice for what shortcut should be used for that intent exists, then it is
1503 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001504 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1505 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001506 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001507 try {
Jason Monk41314972014-03-03 16:11:30 -05001508 metaIntent = Intent.parseUri(intentUri, 0);
1509 } catch (URISyntaxException e) {
1510 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1511 return -1;
1512 }
1513
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001514 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001515 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001516 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001517 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1518
1519 // Verify that the result is an app and not just the resolver dialog asking which
1520 // app to use.
1521 if (wouldLaunchResolverActivity(resolved, appList)) {
1522 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001523 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001524 if (systemApp == null) {
1525 // There is no logical choice for this meta-favorite, so rather than making
1526 // a bad choice just add nothing.
1527 Log.w(TAG, "No preference or single system activity found for "
1528 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001529 return -1;
1530 }
Jason Monk41314972014-03-03 16:11:30 -05001531 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001532 }
Jason Monk41314972014-03-03 16:11:30 -05001533 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001534 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001535 intent.setComponent(new ComponentName(info.packageName, info.name));
1536 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1537 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1538
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001539 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001540 }
1541
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001542 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001543 ResolveInfo systemResolve = null;
1544 final int N = appList.size();
1545 for (int i = 0; i < N; ++i) {
1546 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001547 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001548 appList.get(i).activityInfo.packageName, 0);
1549 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1550 if (systemResolve != null) {
1551 return null;
1552 } else {
1553 systemResolve = appList.get(i);
1554 }
1555 }
1556 } catch (PackageManager.NameNotFoundException e) {
1557 Log.w(TAG, "Unable to get info about resolve results", e);
1558 return null;
1559 }
1560 }
1561 return systemResolve;
1562 }
1563
1564 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1565 List<ResolveInfo> appList) {
1566 // If the list contains the above resolved activity, then it can't be
1567 // ResolverActivity itself.
1568 for (int i = 0; i < appList.size(); ++i) {
1569 ResolveInfo tmp = appList.get(i);
1570 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1571 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1572 return false;
1573 }
1574 }
1575 return true;
1576 }
1577
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001578 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1579 XmlResourceParser parser) {
1580 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1581 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1582 final String uri = getAttributeValue(parser, ATTR_URI);
1583
1584 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001585 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001586 try {
1587 ComponentName cn;
1588 try {
1589 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001590 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001591 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001592 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001593 new String[] { packageName });
1594 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001595 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001596 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001597 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001598 intent.setComponent(cn);
1599 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1600 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1601
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001602 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001603 intent);
1604 } catch (PackageManager.NameNotFoundException e) {
1605 Log.w(TAG, "Unable to add favorite: " + packageName +
1606 "/" + className, e);
1607 }
1608 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001609 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001610 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001611 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001612 } else {
1613 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1614 return -1;
1615 }
1616 }
1617
1618 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1619 Intent intent) {
1620 long id = generateNewItemId();
1621 values.put(Favorites.INTENT, intent.toUri(0));
1622 values.put(Favorites.TITLE, title);
1623 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1624 values.put(Favorites.SPANX, 1);
1625 values.put(Favorites.SPANY, 1);
1626 values.put(Favorites._ID, id);
1627 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1628 return -1;
1629 } else {
1630 return id;
1631 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001632 }
1633
1634 private long addFolder(SQLiteDatabase db, ContentValues values) {
1635 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1636 values.put(Favorites.SPANX, 1);
1637 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001638 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001639 values.put(Favorites._ID, id);
1640 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1641 return -1;
1642 } else {
1643 return id;
1644 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001645 }
1646
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001647 private ComponentName getSearchWidgetProvider() {
1648 SearchManager searchManager =
1649 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1650 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1651 if (searchComponent == null) return null;
1652 return getProviderInPackage(searchComponent.getPackageName());
1653 }
1654
1655 /**
1656 * Gets an appwidget provider from the given package. If the package contains more than
1657 * one appwidget provider, an arbitrary one is returned.
1658 */
1659 private ComponentName getProviderInPackage(String packageName) {
1660 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1661 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1662 if (providers == null) return null;
1663 final int providerCount = providers.size();
1664 for (int i = 0; i < providerCount; i++) {
1665 ComponentName provider = providers.get(i).provider;
1666 if (provider != null && provider.getPackageName().equals(packageName)) {
1667 return provider;
1668 }
1669 }
1670 return null;
1671 }
1672
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001673 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001674 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001675 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001676 }
1677
1678 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001679 ComponentName cn = new ComponentName("com.android.alarmclock",
1680 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001681 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001682 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001683
Winson Chungb3302ae2012-05-01 10:19:14 -07001684 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001685 SQLiteDatabase db, ContentValues values, TypedArray a)
1686 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001687
Mike Cleronb87bd162009-10-30 16:36:56 -07001688 String packageName = a.getString(R.styleable.Favorite_packageName);
1689 String className = a.getString(R.styleable.Favorite_className);
1690
1691 if (packageName == null || className == null) {
1692 return false;
1693 }
Romain Guy693599f2010-03-23 10:58:18 -07001694
1695 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001696 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001697 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001698 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001699 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001700 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001701 new String[] { packageName });
1702 cn = new ComponentName(packages[0], className);
1703 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001704 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001705 } catch (Exception e1) {
1706 hasPackage = false;
1707 }
1708 }
1709
1710 if (hasPackage) {
1711 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1712 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001713
1714 // Read the extras
1715 Bundle extras = new Bundle();
1716 int widgetDepth = parser.getDepth();
1717 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1718 parser.getDepth() > widgetDepth) {
1719 if (type != XmlPullParser.START_TAG) {
1720 continue;
1721 }
1722
1723 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1724 if (TAG_EXTRA.equals(parser.getName())) {
1725 String key = ar.getString(R.styleable.Extra_key);
1726 String value = ar.getString(R.styleable.Extra_value);
1727 if (key != null && value != null) {
1728 extras.putString(key, value);
1729 } else {
1730 throw new RuntimeException("Widget extras must have a key and value");
1731 }
1732 } else {
1733 throw new RuntimeException("Widgets can contain only extras");
1734 }
1735 ar.recycle();
1736 }
1737
1738 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001739 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001740
Romain Guy693599f2010-03-23 10:58:18 -07001741 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001742 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001743 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001744 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001745 boolean allocatedAppWidgets = false;
1746 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1747
1748 try {
1749 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001750
Mike Cleronb87bd162009-10-30 16:36:56 -07001751 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001752 values.put(Favorites.SPANX, spanX);
1753 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001754 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001755 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001756 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001757 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001758
1759 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001760
Michael Jurka8b805b12012-04-18 14:23:14 -07001761 // TODO: need to check return value
1762 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001763
1764 // Send a broadcast to configure the widget
1765 if (extras != null && !extras.isEmpty()) {
1766 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1767 intent.setComponent(cn);
1768 intent.putExtras(extras);
1769 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1770 mContext.sendBroadcast(intent);
1771 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001772 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001773 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001774 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001775
Mike Cleronb87bd162009-10-30 16:36:56 -07001776 return allocatedAppWidgets;
1777 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001778
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001779 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1780 XmlResourceParser parser) {
1781 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1782 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001783
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001784 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001785 String uri = null;
1786 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001787 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001788 intent = Intent.parseUri(uri, 0);
1789 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001790 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001791 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001792 }
1793
1794 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001795 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001796 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001797 }
1798
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001800 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1801 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001802 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001803 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1804 values.put(Favorites.SPANX, 1);
1805 values.put(Favorites.SPANY, 1);
1806 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001807 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1808 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001809 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001810
Adam Cohen228da5a2011-07-27 22:23:47 -07001811 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1812 return -1;
1813 }
1814 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001815 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001816
1817 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1818 final ContentResolver resolver = mContext.getContentResolver();
1819 Cursor c = null;
1820 int count = 0;
1821 int curScreen = 0;
1822
1823 try {
1824 c = resolver.query(uri, null, null, null, "title ASC");
1825 } catch (Exception e) {
1826 // Ignore
1827 }
1828
Dan Sandlerd5024042014-01-09 15:01:33 -05001829 // We already have a favorites database in the old provider
1830 if (c != null) {
1831 try {
1832 if (c.getCount() > 0) {
1833 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1834 final int intentIndex
1835 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1836 final int titleIndex
1837 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1838 final int iconTypeIndex
1839 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1840 final int iconIndex
1841 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1842 final int iconPackageIndex
1843 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1844 final int iconResourceIndex
1845 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1846 final int containerIndex
1847 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1848 final int itemTypeIndex
1849 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1850 final int screenIndex
1851 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1852 final int cellXIndex
1853 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1854 final int cellYIndex
1855 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1856 final int uriIndex
1857 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1858 final int displayModeIndex
1859 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001860 final int profileIndex
1861 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001862
1863 int i = 0;
1864 int curX = 0;
1865 int curY = 0;
1866
1867 final LauncherAppState app = LauncherAppState.getInstance();
1868 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1869 final int width = (int) grid.numColumns;
1870 final int height = (int) grid.numRows;
1871 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001872 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001873
1874 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1875
Adam Cohen72960972014-01-15 18:13:55 -08001876 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1877 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001878 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001879
1880 while (c.moveToNext()) {
1881 final int itemType = c.getInt(itemTypeIndex);
1882 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1883 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1884 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1885 continue;
1886 }
1887
1888 final int cellX = c.getInt(cellXIndex);
1889 final int cellY = c.getInt(cellYIndex);
1890 final int screen = c.getInt(screenIndex);
1891 int container = c.getInt(containerIndex);
1892 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001893
1894 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1895 UserHandleCompat userHandle;
1896 final long userSerialNumber;
1897 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1898 userSerialNumber = c.getInt(profileIndex);
1899 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1900 } else {
1901 // Default to the serial number of this user, for older
1902 // shortcuts.
1903 userHandle = UserHandleCompat.myUserHandle();
1904 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1905 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001906 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001907 + c.getString(titleIndex) + "\" ("
1908 + cellX + "," + cellY + "@"
1909 + LauncherSettings.Favorites.containerToString(container)
1910 + "/" + screen
1911 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001912
1913 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001914
1915 final Intent intent;
1916 final ComponentName cn;
1917 try {
1918 intent = Intent.parseUri(intentStr, 0);
1919 } catch (URISyntaxException e) {
1920 // bogus intent?
1921 Launcher.addDumpLog(TAG,
1922 "skipping invalid intent uri", true);
1923 continue;
1924 }
1925
1926 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001927 if (TextUtils.isEmpty(intentStr)) {
1928 // no intent? no icon
1929 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1930 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001931 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001932 !LauncherModel.isValidPackageActivity(mContext, cn,
1933 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001934 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001935 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001936 "no longer exists.", true);
1937 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001938 } else if (container ==
1939 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1940 // Dedupe icons directly on the workspace
1941
Adam Cohen556f6132014-01-15 15:18:08 -08001942 // Canonicalize
1943 // the Play Store sets the package parameter, but Launcher
1944 // does not, so we clear that out to keep them the same
1945 intent.setPackage(null);
1946 final String key = intent.toUri(0);
1947 if (seenIntents.contains(key)) {
1948 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001949 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001950 } else {
1951 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001952 }
1953 }
1954 }
1955
1956 ContentValues values = new ContentValues(c.getColumnCount());
1957 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1958 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1959 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1960 values.put(LauncherSettings.Favorites.ICON_TYPE,
1961 c.getInt(iconTypeIndex));
1962 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1963 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1964 c.getString(iconPackageIndex));
1965 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1966 c.getString(iconResourceIndex));
1967 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1968 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1969 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1970 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1971 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001972 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001973
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001974 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1975 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001976 }
1977
1978 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1979 // In a folder or in the hotseat, preserve position
1980 values.put(LauncherSettings.Favorites.SCREEN, screen);
1981 values.put(LauncherSettings.Favorites.CELLX, cellX);
1982 values.put(LauncherSettings.Favorites.CELLY, cellY);
1983 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001984 // For items contained directly on one of the workspace screen,
1985 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001986 }
1987
1988 values.put(LauncherSettings.Favorites.CONTAINER, container);
1989
Adam Cohen72960972014-01-15 18:13:55 -08001990 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1991 shortcuts.add(values);
1992 } else {
1993 folders.add(values);
1994 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001995 }
1996
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001997 // Now that we have all the hotseat icons, let's go through them left-right
1998 // and assign valid locations for them in the new hotseat
1999 final int N = hotseat.size();
2000 for (int idx=0; idx<N; idx++) {
2001 int hotseatX = hotseat.keyAt(idx);
2002 ContentValues values = hotseat.valueAt(idx);
2003
2004 if (hotseatX == grid.hotseatAllAppsRank) {
2005 // let's drop this in the next available hole in the hotseat
2006 while (++hotseatX < hotseatWidth) {
2007 if (hotseat.get(hotseatX) == null) {
2008 // found a spot! move it here
2009 values.put(LauncherSettings.Favorites.SCREEN,
2010 hotseatX);
2011 break;
2012 }
2013 }
2014 }
2015 if (hotseatX >= hotseatWidth) {
2016 // no room for you in the hotseat? it's off to the desktop with you
2017 values.put(LauncherSettings.Favorites.CONTAINER,
2018 Favorites.CONTAINER_DESKTOP);
2019 }
2020 }
2021
Adam Cohen72960972014-01-15 18:13:55 -08002022 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2023 // Folders first
2024 allItems.addAll(folders);
2025 // Then shortcuts
2026 allItems.addAll(shortcuts);
2027
2028 // Layout all the folders
2029 for (ContentValues values: allItems) {
2030 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2031 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2032 // Hotseat items and folder items have already had their
2033 // location information set. Nothing to be done here.
2034 continue;
2035 }
2036 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2037 values.put(LauncherSettings.Favorites.CELLX, curX);
2038 values.put(LauncherSettings.Favorites.CELLY, curY);
2039 curX = (curX + 1) % width;
2040 if (curX == 0) {
2041 curY = (curY + 1);
2042 }
2043 // Leave the last row of icons blank on every screen
2044 if (curY == height - 1) {
2045 curScreen = (int) generateNewScreenId();
2046 curY = 0;
2047 }
2048 }
2049
2050 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002051 db.beginTransaction();
2052 try {
Adam Cohen72960972014-01-15 18:13:55 -08002053 for (ContentValues row: allItems) {
2054 if (row == null) continue;
2055 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002056 < 0) {
2057 return;
2058 } else {
2059 count++;
2060 }
2061 }
2062 db.setTransactionSuccessful();
2063 } finally {
2064 db.endTransaction();
2065 }
2066 }
2067
2068 db.beginTransaction();
2069 try {
2070 for (i=0; i<=curScreen; i++) {
2071 final ContentValues values = new ContentValues();
2072 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2073 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2074 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2075 < 0) {
2076 return;
2077 }
2078 }
2079 db.setTransactionSuccessful();
2080 } finally {
2081 db.endTransaction();
2082 }
2083 }
2084 } finally {
2085 c.close();
2086 }
2087 }
2088
2089 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2090 + (curScreen+1) + " screens", true);
2091
2092 // ensure that new screens are created to hold these icons
2093 setFlagJustLoadedOldDb();
2094
2095 // Update max IDs; very important since we just grabbed IDs from another database
2096 mMaxItemId = initializeMaxItemId(db);
2097 mMaxScreenId = initializeMaxScreenId(db);
2098 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2099 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002100 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002101
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002102 /**
2103 * Build a query string that will match any row where the column matches
2104 * anything in the values list.
2105 */
2106 static String buildOrWhereString(String column, int[] values) {
2107 StringBuilder selectWhere = new StringBuilder();
2108 for (int i = values.length - 1; i >= 0; i--) {
2109 selectWhere.append(column).append("=").append(values[i]);
2110 if (i > 0) {
2111 selectWhere.append(" OR ");
2112 }
2113 }
2114 return selectWhere.toString();
2115 }
2116
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002117 /**
2118 * Return attribute value, attempting launcher-specific namespace first
2119 * before falling back to anonymous attribute.
2120 */
2121 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2122 String value = parser.getAttributeValue(
2123 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2124 if (value == null) {
2125 value = parser.getAttributeValue(null, attribute);
2126 }
2127 return value;
2128 }
2129
2130 /**
2131 * Return attribute resource value, attempting launcher-specific namespace
2132 * first before falling back to anonymous attribute.
2133 */
2134 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2135 int defaultValue) {
2136 int value = parser.getAttributeResourceValue(
2137 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2138 defaultValue);
2139 if (value == defaultValue) {
2140 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2141 }
2142 return value;
2143 }
2144
2145 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2146 to.put(key, from.getAsInteger(key));
2147 }
2148
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002149 static class SqlArguments {
2150 public final String table;
2151 public final String where;
2152 public final String[] args;
2153
2154 SqlArguments(Uri url, String where, String[] args) {
2155 if (url.getPathSegments().size() == 1) {
2156 this.table = url.getPathSegments().get(0);
2157 this.where = where;
2158 this.args = args;
2159 } else if (url.getPathSegments().size() != 2) {
2160 throw new IllegalArgumentException("Invalid URI: " + url);
2161 } else if (!TextUtils.isEmpty(where)) {
2162 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2163 } else {
2164 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002165 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002166 this.args = null;
2167 }
2168 }
2169
2170 SqlArguments(Uri url) {
2171 if (url.getPathSegments().size() == 1) {
2172 table = url.getPathSegments().get(0);
2173 where = null;
2174 args = null;
2175 } else {
2176 throw new IllegalArgumentException("Invalid URI: " + url);
2177 }
2178 }
2179 }
Adam Cohen72960972014-01-15 18:13:55 -08002180}