blob: bbc75b8c9d5fa7eede9cf43043c006dd6b9ac329 [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
Adam Cohen9b1d0622014-05-21 19:01:57 -0700876 @Override
877 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
878 // This shouldn't happen -- throw our hands up in the air and start over.
879 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
880 ". Wiping databse.");
881
882 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
883 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
884 onCreate(db);
885 }
886
Kenny Guyed131872014-04-30 03:02:21 +0100887 private boolean addProfileColumn(SQLiteDatabase db) {
888 db.beginTransaction();
889 try {
890 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
891 // Default to the serial number of this user, for older
892 // shortcuts.
893 long userSerialNumber = userManager.getSerialNumberForUser(
894 UserHandleCompat.myUserHandle());
895 // Insert new column for holding user serial number
896 db.execSQL("ALTER TABLE favorites " +
897 "ADD COLUMN profileId INTEGER DEFAULT "
898 + userSerialNumber + ";");
899 db.setTransactionSuccessful();
900 } catch (SQLException ex) {
901 // Old version remains, which means we wipe old data
902 Log.e(TAG, ex.getMessage(), ex);
903 return false;
904 } finally {
905 db.endTransaction();
906 }
907 return true;
908 }
909
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800910 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800911 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
912 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
913
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700914 Cursor c = null;
915 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800916 db.beginTransaction();
917 try {
918 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700919 c = db.query(TABLE_FAVORITES,
920 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800921 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700922 if (c == null) return false;
923
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800924 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700925
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800926 final int idIndex = c.getColumnIndex(Favorites._ID);
927 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700928
929 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800930 long favoriteId = c.getLong(idIndex);
931 final String intentUri = c.getString(intentIndex);
932 if (intentUri != null) {
933 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700934 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800935 android.util.Log.d("Home", intent.toString());
936 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700937 if (uri != null) {
938 final String data = uri.toString();
939 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
940 actionQuickContact.equals(intent.getAction())) &&
941 (data.startsWith("content://contacts/people/") ||
942 data.startsWith("content://com.android.contacts/" +
943 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800944
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700945 final Intent newIntent = new Intent(actionQuickContact);
946 // When starting from the launcher, start in a new, cleared task
947 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
948 // clear the whole thing preemptively here since
949 // QuickContactActivity will finish itself when launching other
950 // detail activities.
951 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
952 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700953 newIntent.putExtra(
954 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700955 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700956 // Determine the type and also put that in the shortcut
957 // (that can speed up launch a bit)
958 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800959
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700960 final ContentValues values = new ContentValues();
961 values.put(LauncherSettings.Favorites.INTENT,
962 newIntent.toUri(0));
963
964 String updateWhere = Favorites._ID + "=" + favoriteId;
965 db.update(TABLE_FAVORITES, values, updateWhere, null);
966 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800967 }
968 } catch (RuntimeException ex) {
969 Log.e(TAG, "Problem upgrading shortcut", ex);
970 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700971 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800972 }
973 }
974 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700975
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800976 db.setTransactionSuccessful();
977 } catch (SQLException ex) {
978 Log.w(TAG, "Problem while upgrading contacts", ex);
979 return false;
980 } finally {
981 db.endTransaction();
982 if (c != null) {
983 c.close();
984 }
985 }
986
987 return true;
988 }
989
Joe Onorato0589f0f2010-02-08 13:44:00 -0800990 private void normalizeIcons(SQLiteDatabase db) {
991 Log.d(TAG, "normalizing icons");
992
Joe Onorato346e1292010-02-18 10:34:24 -0500993 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800994 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400995 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800996 try {
997 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400998 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600999 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -08001000
1001 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
1002 Favorites.ICON_TYPE_BITMAP, null);
1003
1004 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1005 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
1006
1007 while (c.moveToNext()) {
1008 long id = c.getLong(idIndex);
1009 byte[] data = c.getBlob(iconIndex);
1010 try {
1011 Bitmap bitmap = Utilities.resampleIconBitmap(
1012 BitmapFactory.decodeByteArray(data, 0, data.length),
1013 mContext);
1014 if (bitmap != null) {
1015 update.bindLong(1, id);
1016 data = ItemInfo.flattenBitmap(bitmap);
1017 if (data != null) {
1018 update.bindBlob(2, data);
1019 update.execute();
1020 }
1021 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001022 }
1023 } catch (Exception e) {
1024 if (!logged) {
1025 Log.e(TAG, "Failed normalizing icon " + id, e);
1026 } else {
1027 Log.e(TAG, "Also failed normalizing icon " + id);
1028 }
1029 logged = true;
1030 }
1031 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001032 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001033 } catch (SQLException ex) {
1034 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1035 } finally {
1036 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001037 if (update != null) {
1038 update.close();
1039 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001040 if (c != null) {
1041 c.close();
1042 }
1043 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 }
1045
1046 // Generates a new ID to use for an object in your database. This method should be only
1047 // called from the main UI thread. As an exception, we do call it when we call the
1048 // constructor from the worker thread; however, this doesn't extend until after the
1049 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1050 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001051 public long generateNewItemId() {
1052 if (mMaxItemId < 0) {
1053 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001054 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001055 mMaxItemId += 1;
1056 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001057 }
1058
Winson Chungc763c4e2013-07-19 13:49:06 -07001059 public void updateMaxItemId(long id) {
1060 mMaxItemId = id + 1;
1061 }
1062
Chris Wren5dee7af2013-12-20 17:22:11 -05001063 public void checkId(String table, ContentValues values) {
1064 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1065 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1066 mMaxScreenId = Math.max(id, mMaxScreenId);
1067 } else {
1068 mMaxItemId = Math.max(id, mMaxItemId);
1069 }
1070 }
1071
Adam Cohendcd297f2013-06-18 13:13:40 -07001072 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001073 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1074
1075 // get the result
1076 final int maxIdIndex = 0;
1077 long id = -1;
1078 if (c != null && c.moveToNext()) {
1079 id = c.getLong(maxIdIndex);
1080 }
Michael Jurka5130e402011-10-13 04:55:35 -07001081 if (c != null) {
1082 c.close();
1083 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001084
1085 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001086 throw new RuntimeException("Error: could not query max item id");
1087 }
1088
1089 return id;
1090 }
1091
1092 // Generates a new ID to use for an workspace screen in your database. This method
1093 // should be only called from the main UI thread. As an exception, we do call it when we
1094 // call the constructor from the worker thread; however, this doesn't extend until after the
1095 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1096 // after that point
1097 public long generateNewScreenId() {
1098 if (mMaxScreenId < 0) {
1099 throw new RuntimeException("Error: max screen id was not initialized");
1100 }
1101 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001102 // Log to disk
1103 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001104 return mMaxScreenId;
1105 }
1106
1107 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001108 // Log to disk
1109 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001110 mMaxScreenId = maxScreenId;
1111 }
1112
1113 private long initializeMaxScreenId(SQLiteDatabase db) {
1114 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1115
1116 // get the result
1117 final int maxIdIndex = 0;
1118 long id = -1;
1119 if (c != null && c.moveToNext()) {
1120 id = c.getLong(maxIdIndex);
1121 }
1122 if (c != null) {
1123 c.close();
1124 }
1125
1126 if (id == -1) {
1127 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001128 }
1129
Winson Chunga90303b2013-11-15 13:05:06 -08001130 // Log to disk
1131 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001132 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001133 }
1134
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001135 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001136 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001137 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 */
1139 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001140 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001141 final int[] bindSources = new int[] {
1142 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1143 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001144 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001145 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001146
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001147 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001148
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001149 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001150
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001151 db.beginTransaction();
1152 try {
1153 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001154 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001155 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001156
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001157 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001158
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001159 final ContentValues values = new ContentValues();
1160 while (c != null && c.moveToNext()) {
1161 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001162 int favoriteType = c.getInt(1);
1163
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001164 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001165 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001166 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001167
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001168 if (LOGD) {
1169 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1170 + " for favoriteId=" + favoriteId);
1171 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001172 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001173 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1174 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1175
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001176 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001177 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1178 values.put(LauncherSettings.Favorites.SPANX, 4);
1179 values.put(LauncherSettings.Favorites.SPANY, 1);
1180 } else {
1181 values.put(LauncherSettings.Favorites.SPANX, 2);
1182 values.put(LauncherSettings.Favorites.SPANY, 2);
1183 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001184
1185 String updateWhere = Favorites._ID + "=" + favoriteId;
1186 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001187
Bjorn Bringert34251342009-12-15 13:33:11 +00001188 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001189 // TODO: check return value
1190 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001191 new ComponentName("com.android.alarmclock",
1192 "com.android.alarmclock.AnalogAppWidgetProvider"));
1193 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001194 // TODO: check return value
1195 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001196 new ComponentName("com.android.camera",
1197 "com.android.camera.PhotoAppWidgetProvider"));
1198 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001199 // TODO: check return value
1200 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001201 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001202 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001203 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001204 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001205 }
1206 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001207
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 db.setTransactionSuccessful();
1209 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001210 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001211 } finally {
1212 db.endTransaction();
1213 if (c != null) {
1214 c.close();
1215 }
1216 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001217
1218 // Update max item id
1219 mMaxItemId = initializeMaxItemId(db);
1220 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001221 }
1222
Michael Jurka8b805b12012-04-18 14:23:14 -07001223 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1224 throws XmlPullParserException, IOException {
1225 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001226 while ((type = parser.next()) != XmlPullParser.START_TAG
1227 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001228 ;
1229 }
1230
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001231 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001232 throw new XmlPullParserException("No start tag found");
1233 }
1234
1235 if (!parser.getName().equals(firstElementName)) {
1236 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1237 ", expected " + firstElementName);
1238 }
1239 }
1240
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001241 private static Intent buildMainIntent() {
1242 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1243 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1244 return intent;
1245 }
1246
Adam Cohen71483f42014-05-15 14:04:01 -07001247 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
1248 ArrayList<Long> screenIds = new ArrayList<Long>();
1249 int count = loadFavoritesRecursive(db, workspaceResourceId, screenIds);
1250
1251 // Add the screens specified by the items above
1252 Collections.sort(screenIds);
1253 int rank = 0;
1254 ContentValues values = new ContentValues();
1255 for (Long id : screenIds) {
1256 values.clear();
1257 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1258 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1259 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1260 throw new RuntimeException("Failed initialize screen table"
1261 + "from default layout");
1262 }
1263 rank++;
1264 }
1265
1266 // Ensure that the max ids are initialized
1267 mMaxItemId = initializeMaxItemId(db);
1268 mMaxScreenId = initializeMaxScreenId(db);
1269 return count;
1270 }
1271
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001272 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001273 * Loads the default set of favorite packages from an xml file.
1274 *
1275 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001276 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001277 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001278 */
Adam Cohen71483f42014-05-15 14:04:01 -07001279 private int loadFavoritesRecursive(SQLiteDatabase db, int workspaceResourceId,
1280 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001281
Adam Cohen71483f42014-05-15 14:04:01 -07001282
1283
1284 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001285 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1286
Adam Cohen71483f42014-05-15 14:04:01 -07001287 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001288 try {
Winson Chung6d092682011-11-16 18:43:26 -08001289 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001290 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001291 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001292
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001293 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001294
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001295 int type;
1296 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1297 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1298
1299 if (type != XmlPullParser.START_TAG) {
1300 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001301 }
1302
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001303 boolean added = false;
1304 final String name = parser.getName();
1305
Daniel Sandler57dac262013-10-03 13:28:36 -04001306 if (TAG_INCLUDE.equals(name)) {
1307 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1308
1309 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1310
1311 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1312 "", resId));
1313
1314 if (resId != 0 && resId != workspaceResourceId) {
1315 // recursively load some more favorites, why not?
Adam Cohen71483f42014-05-15 14:04:01 -07001316 count += loadFavoritesRecursive(db, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001317 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001318 } else {
1319 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1320 }
1321
1322 a.recycle();
1323
1324 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1325 continue;
1326 }
1327
1328 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001329 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1330
Winson Chung3d503fb2011-07-13 17:25:49 -07001331 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1332 if (a.hasValue(R.styleable.Favorite_container)) {
1333 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1334 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001335
Winson Chung6d092682011-11-16 18:43:26 -08001336 String screen = a.getString(R.styleable.Favorite_screen);
1337 String x = a.getString(R.styleable.Favorite_x);
1338 String y = a.getString(R.styleable.Favorite_y);
1339
Winson Chung6d092682011-11-16 18:43:26 -08001340 values.clear();
1341 values.put(LauncherSettings.Favorites.CONTAINER, container);
1342 values.put(LauncherSettings.Favorites.SCREEN, screen);
1343 values.put(LauncherSettings.Favorites.CELLX, x);
1344 values.put(LauncherSettings.Favorites.CELLY, y);
1345
Daniel Sandler57dac262013-10-03 13:28:36 -04001346 if (LOGD) {
1347 final String title = a.getString(R.styleable.Favorite_title);
1348 final String pkg = a.getString(R.styleable.Favorite_packageName);
1349 final String something = title != null ? title : pkg;
1350 Log.v(TAG, String.format(
1351 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1352 "", name,
1353 (something == null ? "" : (" \"" + something + "\"")),
1354 container, screen, x, y));
1355 }
1356
Winson Chung6d092682011-11-16 18:43:26 -08001357 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001358 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001359 added = id >= 0;
1360 } else if (TAG_SEARCH.equals(name)) {
1361 added = addSearchWidget(db, values);
1362 } else if (TAG_CLOCK.equals(name)) {
1363 added = addClockWidget(db, values);
1364 } else if (TAG_APPWIDGET.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001365 added = addAppWidget(parser, attrs, type, db, values, a);
Winson Chung6d092682011-11-16 18:43:26 -08001366 } else if (TAG_SHORTCUT.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001367 long id = addUriShortcut(db, values, mContext.getResources(), parser);
Winson Chung6d092682011-11-16 18:43:26 -08001368 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001369 } else if (TAG_RESOLVE.equals(name)) {
1370 // This looks through the contained favorites (or meta-favorites) and
1371 // attempts to add them as shortcuts in the fallback group's location
1372 // until one is added successfully.
1373 added = false;
1374 final int groupDepth = parser.getDepth();
1375 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1376 parser.getDepth() > groupDepth) {
1377 if (type != XmlPullParser.START_TAG) {
1378 continue;
1379 }
1380 final String fallback_item_name = parser.getName();
1381 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1382 R.styleable.Favorite);
1383 if (!added) {
1384 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001385 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001386 added = id >= 0;
1387 } else {
1388 Log.e(TAG, "Fallback groups can contain only favorites "
1389 + ar.toString());
1390 }
1391 }
1392 ar.recycle();
1393 }
Winson Chung6d092682011-11-16 18:43:26 -08001394 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001395 // Folder contents are nested in this XML file
1396 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001397
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001398 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1399 // Folder contents come from an external XML resource
1400 final Partner partner = Partner.get(mPackageManager);
1401 if (partner != null) {
1402 final Resources partnerRes = partner.getResources();
1403 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1404 "xml", partner.getPackageName());
1405 if (resId != 0) {
1406 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1407 beginDocument(partnerParser, TAG_FOLDER);
1408 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001409 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001410 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001411 }
Adam Cohen71483f42014-05-15 14:04:01 -07001412 if (added) {
1413 long screenId = Long.parseLong(screen);
1414 // Keep track of the set of screens which need to be added to the db.
1415 if (!screenIds.contains(screenId) &&
1416 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1417 screenIds.add(screenId);
1418 }
1419 count++;
1420 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001421 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001422 }
1423 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001424 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001425 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001426 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001427 } catch (RuntimeException e) {
1428 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001429 }
Adam Cohen71483f42014-05-15 14:04:01 -07001430 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001431 }
1432
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001433 /**
1434 * Parse folder starting at current {@link XmlPullParser} location.
1435 */
1436 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1437 XmlResourceParser parser) throws IOException, XmlPullParserException {
1438 final String title;
1439 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1440 if (titleResId != 0) {
1441 title = res.getString(titleResId);
1442 } else {
1443 title = mContext.getResources().getString(R.string.folder_name);
1444 }
1445
1446 values.put(LauncherSettings.Favorites.TITLE, title);
1447 long folderId = addFolder(db, values);
1448 boolean added = folderId >= 0;
1449
1450 ArrayList<Long> folderItems = new ArrayList<Long>();
1451
1452 int type;
1453 int folderDepth = parser.getDepth();
1454 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1455 parser.getDepth() > folderDepth) {
1456 if (type != XmlPullParser.START_TAG) {
1457 continue;
1458 }
1459 final String tag = parser.getName();
1460
1461 final ContentValues childValues = new ContentValues();
1462 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1463
1464 if (LOGD) {
1465 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1466 final String uri = getAttributeValue(parser, ATTR_URI);
1467 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1468 tag, uri != null ? uri : pkg));
1469 }
1470
1471 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1472 final long id = addAppShortcut(db, childValues, parser);
1473 if (id >= 0) {
1474 folderItems.add(id);
1475 }
1476 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1477 final long id = addUriShortcut(db, childValues, res, parser);
1478 if (id >= 0) {
1479 folderItems.add(id);
1480 }
1481 } else {
1482 throw new RuntimeException("Folders can contain only shortcuts");
1483 }
1484 }
1485
1486 // We can only have folders with >= 2 items, so we need to remove the
1487 // folder and clean up if less than 2 items were included, or some
1488 // failed to add, and less than 2 were actually added
1489 if (folderItems.size() < 2 && folderId >= 0) {
1490 // Delete the folder
1491 deleteId(db, folderId);
1492
1493 // If we have a single item, promote it to where the folder
1494 // would have been.
1495 if (folderItems.size() == 1) {
1496 final ContentValues childValues = new ContentValues();
1497 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1498 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1499 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1500 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1501
1502 final long id = folderItems.get(0);
1503 db.update(TABLE_FAVORITES, childValues,
1504 LauncherSettings.Favorites._ID + "=" + id, null);
1505 } else {
1506 added = false;
1507 }
1508 }
1509 return added;
1510 }
1511
Jason Monk41314972014-03-03 16:11:30 -05001512 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1513 // logical choice for what shortcut should be used for that intent exists, then it is
1514 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001515 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1516 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001517 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001518 try {
Jason Monk41314972014-03-03 16:11:30 -05001519 metaIntent = Intent.parseUri(intentUri, 0);
1520 } catch (URISyntaxException e) {
1521 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1522 return -1;
1523 }
1524
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001525 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001526 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001527 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001528 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1529
1530 // Verify that the result is an app and not just the resolver dialog asking which
1531 // app to use.
1532 if (wouldLaunchResolverActivity(resolved, appList)) {
1533 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001534 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001535 if (systemApp == null) {
1536 // There is no logical choice for this meta-favorite, so rather than making
1537 // a bad choice just add nothing.
1538 Log.w(TAG, "No preference or single system activity found for "
1539 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001540 return -1;
1541 }
Jason Monk41314972014-03-03 16:11:30 -05001542 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001543 }
Jason Monk41314972014-03-03 16:11:30 -05001544 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001545 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001546 intent.setComponent(new ComponentName(info.packageName, info.name));
1547 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1548 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1549
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001550 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001551 }
1552
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001553 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001554 ResolveInfo systemResolve = null;
1555 final int N = appList.size();
1556 for (int i = 0; i < N; ++i) {
1557 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001558 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001559 appList.get(i).activityInfo.packageName, 0);
1560 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1561 if (systemResolve != null) {
1562 return null;
1563 } else {
1564 systemResolve = appList.get(i);
1565 }
1566 }
1567 } catch (PackageManager.NameNotFoundException e) {
1568 Log.w(TAG, "Unable to get info about resolve results", e);
1569 return null;
1570 }
1571 }
1572 return systemResolve;
1573 }
1574
1575 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1576 List<ResolveInfo> appList) {
1577 // If the list contains the above resolved activity, then it can't be
1578 // ResolverActivity itself.
1579 for (int i = 0; i < appList.size(); ++i) {
1580 ResolveInfo tmp = appList.get(i);
1581 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1582 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1583 return false;
1584 }
1585 }
1586 return true;
1587 }
1588
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001589 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1590 XmlResourceParser parser) {
1591 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1592 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1593 final String uri = getAttributeValue(parser, ATTR_URI);
1594
1595 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001596 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001597 try {
1598 ComponentName cn;
1599 try {
1600 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001601 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001602 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001603 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001604 new String[] { packageName });
1605 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001606 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001607 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001608 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001609 intent.setComponent(cn);
1610 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1611 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1612
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001613 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001614 intent);
1615 } catch (PackageManager.NameNotFoundException e) {
1616 Log.w(TAG, "Unable to add favorite: " + packageName +
1617 "/" + className, e);
1618 }
1619 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001620 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001621 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001622 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001623 } else {
1624 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1625 return -1;
1626 }
1627 }
1628
1629 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1630 Intent intent) {
1631 long id = generateNewItemId();
1632 values.put(Favorites.INTENT, intent.toUri(0));
1633 values.put(Favorites.TITLE, title);
1634 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1635 values.put(Favorites.SPANX, 1);
1636 values.put(Favorites.SPANY, 1);
1637 values.put(Favorites._ID, id);
1638 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1639 return -1;
1640 } else {
1641 return id;
1642 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001643 }
1644
1645 private long addFolder(SQLiteDatabase db, ContentValues values) {
1646 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1647 values.put(Favorites.SPANX, 1);
1648 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001649 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001650 values.put(Favorites._ID, id);
1651 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1652 return -1;
1653 } else {
1654 return id;
1655 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001656 }
1657
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001658 private ComponentName getSearchWidgetProvider() {
1659 SearchManager searchManager =
1660 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1661 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1662 if (searchComponent == null) return null;
1663 return getProviderInPackage(searchComponent.getPackageName());
1664 }
1665
1666 /**
1667 * Gets an appwidget provider from the given package. If the package contains more than
1668 * one appwidget provider, an arbitrary one is returned.
1669 */
1670 private ComponentName getProviderInPackage(String packageName) {
1671 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1672 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1673 if (providers == null) return null;
1674 final int providerCount = providers.size();
1675 for (int i = 0; i < providerCount; i++) {
1676 ComponentName provider = providers.get(i).provider;
1677 if (provider != null && provider.getPackageName().equals(packageName)) {
1678 return provider;
1679 }
1680 }
1681 return null;
1682 }
1683
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001684 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001685 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001686 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001687 }
1688
1689 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001690 ComponentName cn = new ComponentName("com.android.alarmclock",
1691 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001692 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001693 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001694
Winson Chungb3302ae2012-05-01 10:19:14 -07001695 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001696 SQLiteDatabase db, ContentValues values, TypedArray a)
1697 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001698
Mike Cleronb87bd162009-10-30 16:36:56 -07001699 String packageName = a.getString(R.styleable.Favorite_packageName);
1700 String className = a.getString(R.styleable.Favorite_className);
1701
1702 if (packageName == null || className == null) {
1703 return false;
1704 }
Romain Guy693599f2010-03-23 10:58:18 -07001705
1706 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001707 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001708 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001709 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001710 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001711 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001712 new String[] { packageName });
1713 cn = new ComponentName(packages[0], className);
1714 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001715 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001716 } catch (Exception e1) {
1717 hasPackage = false;
1718 }
1719 }
1720
1721 if (hasPackage) {
1722 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1723 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001724
1725 // Read the extras
1726 Bundle extras = new Bundle();
1727 int widgetDepth = parser.getDepth();
1728 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1729 parser.getDepth() > widgetDepth) {
1730 if (type != XmlPullParser.START_TAG) {
1731 continue;
1732 }
1733
1734 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1735 if (TAG_EXTRA.equals(parser.getName())) {
1736 String key = ar.getString(R.styleable.Extra_key);
1737 String value = ar.getString(R.styleable.Extra_value);
1738 if (key != null && value != null) {
1739 extras.putString(key, value);
1740 } else {
1741 throw new RuntimeException("Widget extras must have a key and value");
1742 }
1743 } else {
1744 throw new RuntimeException("Widgets can contain only extras");
1745 }
1746 ar.recycle();
1747 }
1748
1749 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001750 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001751
Romain Guy693599f2010-03-23 10:58:18 -07001752 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001753 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001754 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001755 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001756 boolean allocatedAppWidgets = false;
1757 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1758
1759 try {
1760 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001761
Mike Cleronb87bd162009-10-30 16:36:56 -07001762 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001763 values.put(Favorites.SPANX, spanX);
1764 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001765 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001766 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001768 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001769
1770 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001771
Michael Jurka8b805b12012-04-18 14:23:14 -07001772 // TODO: need to check return value
1773 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001774
1775 // Send a broadcast to configure the widget
1776 if (extras != null && !extras.isEmpty()) {
1777 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1778 intent.setComponent(cn);
1779 intent.putExtras(extras);
1780 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1781 mContext.sendBroadcast(intent);
1782 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001783 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001784 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001785 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001786
Mike Cleronb87bd162009-10-30 16:36:56 -07001787 return allocatedAppWidgets;
1788 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001789
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001790 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1791 XmlResourceParser parser) {
1792 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1793 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001794
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001795 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001796 String uri = null;
1797 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001798 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001799 intent = Intent.parseUri(uri, 0);
1800 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001801 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001802 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001803 }
1804
1805 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001806 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001807 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001808 }
1809
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001811 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1812 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001813 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001814 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1815 values.put(Favorites.SPANX, 1);
1816 values.put(Favorites.SPANY, 1);
1817 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001818 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1819 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001820 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001821
Adam Cohen228da5a2011-07-27 22:23:47 -07001822 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1823 return -1;
1824 }
1825 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001826 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001827
1828 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1829 final ContentResolver resolver = mContext.getContentResolver();
1830 Cursor c = null;
1831 int count = 0;
1832 int curScreen = 0;
1833
1834 try {
1835 c = resolver.query(uri, null, null, null, "title ASC");
1836 } catch (Exception e) {
1837 // Ignore
1838 }
1839
Dan Sandlerd5024042014-01-09 15:01:33 -05001840 // We already have a favorites database in the old provider
1841 if (c != null) {
1842 try {
1843 if (c.getCount() > 0) {
1844 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1845 final int intentIndex
1846 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1847 final int titleIndex
1848 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1849 final int iconTypeIndex
1850 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1851 final int iconIndex
1852 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1853 final int iconPackageIndex
1854 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1855 final int iconResourceIndex
1856 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1857 final int containerIndex
1858 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1859 final int itemTypeIndex
1860 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1861 final int screenIndex
1862 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1863 final int cellXIndex
1864 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1865 final int cellYIndex
1866 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1867 final int uriIndex
1868 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1869 final int displayModeIndex
1870 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001871 final int profileIndex
1872 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001873
1874 int i = 0;
1875 int curX = 0;
1876 int curY = 0;
1877
1878 final LauncherAppState app = LauncherAppState.getInstance();
1879 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1880 final int width = (int) grid.numColumns;
1881 final int height = (int) grid.numRows;
1882 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001883 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001884
1885 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1886
Adam Cohen72960972014-01-15 18:13:55 -08001887 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1888 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001889 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001890
1891 while (c.moveToNext()) {
1892 final int itemType = c.getInt(itemTypeIndex);
1893 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1894 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1895 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1896 continue;
1897 }
1898
1899 final int cellX = c.getInt(cellXIndex);
1900 final int cellY = c.getInt(cellYIndex);
1901 final int screen = c.getInt(screenIndex);
1902 int container = c.getInt(containerIndex);
1903 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001904
1905 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1906 UserHandleCompat userHandle;
1907 final long userSerialNumber;
1908 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1909 userSerialNumber = c.getInt(profileIndex);
1910 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1911 } else {
1912 // Default to the serial number of this user, for older
1913 // shortcuts.
1914 userHandle = UserHandleCompat.myUserHandle();
1915 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1916 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001917 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001918 + c.getString(titleIndex) + "\" ("
1919 + cellX + "," + cellY + "@"
1920 + LauncherSettings.Favorites.containerToString(container)
1921 + "/" + screen
1922 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001923
1924 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001925
1926 final Intent intent;
1927 final ComponentName cn;
1928 try {
1929 intent = Intent.parseUri(intentStr, 0);
1930 } catch (URISyntaxException e) {
1931 // bogus intent?
1932 Launcher.addDumpLog(TAG,
1933 "skipping invalid intent uri", true);
1934 continue;
1935 }
1936
1937 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001938 if (TextUtils.isEmpty(intentStr)) {
1939 // no intent? no icon
1940 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1941 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001942 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001943 !LauncherModel.isValidPackageActivity(mContext, cn,
1944 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001945 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001946 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001947 "no longer exists.", true);
1948 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001949 } else if (container ==
1950 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1951 // Dedupe icons directly on the workspace
1952
Adam Cohen556f6132014-01-15 15:18:08 -08001953 // Canonicalize
1954 // the Play Store sets the package parameter, but Launcher
1955 // does not, so we clear that out to keep them the same
1956 intent.setPackage(null);
1957 final String key = intent.toUri(0);
1958 if (seenIntents.contains(key)) {
1959 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001960 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001961 } else {
1962 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001963 }
1964 }
1965 }
1966
1967 ContentValues values = new ContentValues(c.getColumnCount());
1968 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1969 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1970 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1971 values.put(LauncherSettings.Favorites.ICON_TYPE,
1972 c.getInt(iconTypeIndex));
1973 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1974 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1975 c.getString(iconPackageIndex));
1976 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1977 c.getString(iconResourceIndex));
1978 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1979 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1980 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1981 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1982 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001983 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001984
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001985 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1986 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001987 }
1988
1989 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1990 // In a folder or in the hotseat, preserve position
1991 values.put(LauncherSettings.Favorites.SCREEN, screen);
1992 values.put(LauncherSettings.Favorites.CELLX, cellX);
1993 values.put(LauncherSettings.Favorites.CELLY, cellY);
1994 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001995 // For items contained directly on one of the workspace screen,
1996 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001997 }
1998
1999 values.put(LauncherSettings.Favorites.CONTAINER, container);
2000
Adam Cohen72960972014-01-15 18:13:55 -08002001 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
2002 shortcuts.add(values);
2003 } else {
2004 folders.add(values);
2005 }
Dan Sandlerd5024042014-01-09 15:01:33 -05002006 }
2007
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05002008 // Now that we have all the hotseat icons, let's go through them left-right
2009 // and assign valid locations for them in the new hotseat
2010 final int N = hotseat.size();
2011 for (int idx=0; idx<N; idx++) {
2012 int hotseatX = hotseat.keyAt(idx);
2013 ContentValues values = hotseat.valueAt(idx);
2014
2015 if (hotseatX == grid.hotseatAllAppsRank) {
2016 // let's drop this in the next available hole in the hotseat
2017 while (++hotseatX < hotseatWidth) {
2018 if (hotseat.get(hotseatX) == null) {
2019 // found a spot! move it here
2020 values.put(LauncherSettings.Favorites.SCREEN,
2021 hotseatX);
2022 break;
2023 }
2024 }
2025 }
2026 if (hotseatX >= hotseatWidth) {
2027 // no room for you in the hotseat? it's off to the desktop with you
2028 values.put(LauncherSettings.Favorites.CONTAINER,
2029 Favorites.CONTAINER_DESKTOP);
2030 }
2031 }
2032
Adam Cohen72960972014-01-15 18:13:55 -08002033 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2034 // Folders first
2035 allItems.addAll(folders);
2036 // Then shortcuts
2037 allItems.addAll(shortcuts);
2038
2039 // Layout all the folders
2040 for (ContentValues values: allItems) {
2041 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2042 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2043 // Hotseat items and folder items have already had their
2044 // location information set. Nothing to be done here.
2045 continue;
2046 }
2047 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2048 values.put(LauncherSettings.Favorites.CELLX, curX);
2049 values.put(LauncherSettings.Favorites.CELLY, curY);
2050 curX = (curX + 1) % width;
2051 if (curX == 0) {
2052 curY = (curY + 1);
2053 }
2054 // Leave the last row of icons blank on every screen
2055 if (curY == height - 1) {
2056 curScreen = (int) generateNewScreenId();
2057 curY = 0;
2058 }
2059 }
2060
2061 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002062 db.beginTransaction();
2063 try {
Adam Cohen72960972014-01-15 18:13:55 -08002064 for (ContentValues row: allItems) {
2065 if (row == null) continue;
2066 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002067 < 0) {
2068 return;
2069 } else {
2070 count++;
2071 }
2072 }
2073 db.setTransactionSuccessful();
2074 } finally {
2075 db.endTransaction();
2076 }
2077 }
2078
2079 db.beginTransaction();
2080 try {
2081 for (i=0; i<=curScreen; i++) {
2082 final ContentValues values = new ContentValues();
2083 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2084 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2085 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2086 < 0) {
2087 return;
2088 }
2089 }
2090 db.setTransactionSuccessful();
2091 } finally {
2092 db.endTransaction();
2093 }
2094 }
2095 } finally {
2096 c.close();
2097 }
2098 }
2099
2100 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2101 + (curScreen+1) + " screens", true);
2102
2103 // ensure that new screens are created to hold these icons
2104 setFlagJustLoadedOldDb();
2105
2106 // Update max IDs; very important since we just grabbed IDs from another database
2107 mMaxItemId = initializeMaxItemId(db);
2108 mMaxScreenId = initializeMaxScreenId(db);
2109 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2110 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002111 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002112
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002113 /**
2114 * Build a query string that will match any row where the column matches
2115 * anything in the values list.
2116 */
2117 static String buildOrWhereString(String column, int[] values) {
2118 StringBuilder selectWhere = new StringBuilder();
2119 for (int i = values.length - 1; i >= 0; i--) {
2120 selectWhere.append(column).append("=").append(values[i]);
2121 if (i > 0) {
2122 selectWhere.append(" OR ");
2123 }
2124 }
2125 return selectWhere.toString();
2126 }
2127
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002128 /**
2129 * Return attribute value, attempting launcher-specific namespace first
2130 * before falling back to anonymous attribute.
2131 */
2132 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2133 String value = parser.getAttributeValue(
2134 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2135 if (value == null) {
2136 value = parser.getAttributeValue(null, attribute);
2137 }
2138 return value;
2139 }
2140
2141 /**
2142 * Return attribute resource value, attempting launcher-specific namespace
2143 * first before falling back to anonymous attribute.
2144 */
2145 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2146 int defaultValue) {
2147 int value = parser.getAttributeResourceValue(
2148 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2149 defaultValue);
2150 if (value == defaultValue) {
2151 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2152 }
2153 return value;
2154 }
2155
2156 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2157 to.put(key, from.getAsInteger(key));
2158 }
2159
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002160 static class SqlArguments {
2161 public final String table;
2162 public final String where;
2163 public final String[] args;
2164
2165 SqlArguments(Uri url, String where, String[] args) {
2166 if (url.getPathSegments().size() == 1) {
2167 this.table = url.getPathSegments().get(0);
2168 this.where = where;
2169 this.args = args;
2170 } else if (url.getPathSegments().size() != 2) {
2171 throw new IllegalArgumentException("Invalid URI: " + url);
2172 } else if (!TextUtils.isEmpty(where)) {
2173 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2174 } else {
2175 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002176 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002177 this.args = null;
2178 }
2179 }
2180
2181 SqlArguments(Uri url) {
2182 if (url.getPathSegments().size() == 1) {
2183 table = url.getPathSegments().get(0);
2184 where = null;
2185 args = null;
2186 } else {
2187 throw new IllegalArgumentException("Invalid URI: " + url);
2188 }
2189 }
2190 }
Adam Cohen72960972014-01-15 18:13:55 -08002191}