blob: 4a5096564ac09b11cf0f5b16b32a084b2e58c719 [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() {
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -0800339 if (LauncherAppState.isDisableAllApps()) {
Nilesh Agrawalda41ea62013-12-09 14:17:49 -0800340 return R.xml.default_workspace_no_all_apps;
341 } else {
342 return R.xml.default_workspace;
343 }
344 }
345
Winson Chungc763c4e2013-07-19 13:49:06 -0700346 private static interface ContentValuesCallback {
347 public void onRow(ContentValues values);
348 }
349
Adam Cohen6dbe0492013-12-02 17:00:14 -0800350 private static boolean shouldImportLauncher2Database(Context context) {
351 boolean isTablet = context.getResources().getBoolean(R.bool.is_tablet);
352
353 // We don't import the old databse for tablets, as the grid size has changed.
354 return !isTablet && IMPORT_LAUNCHER2_DATABASE;
355 }
356
Dan Sandlerd5024042014-01-09 15:01:33 -0500357 public void deleteDatabase() {
358 // Are you sure? (y/n)
359 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500360 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500361 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500362 if (dbFile.exists()) {
363 SQLiteDatabase.deleteDatabase(dbFile);
364 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500365 mOpenHelper = new DatabaseHelper(getContext());
366 }
367
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 private static class DatabaseHelper extends SQLiteOpenHelper {
Jason Monk41314972014-03-03 16:11:30 -0500369 private static final String TAG_RESOLVE = "resolve";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800370 private static final String TAG_FAVORITES = "favorites";
371 private static final String TAG_FAVORITE = "favorite";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700372 private static final String TAG_CLOCK = "clock";
373 private static final String TAG_SEARCH = "search";
Mike Cleronb87bd162009-10-30 16:36:56 -0700374 private static final String TAG_APPWIDGET = "appwidget";
375 private static final String TAG_SHORTCUT = "shortcut";
Adam Cohen228da5a2011-07-27 22:23:47 -0700376 private static final String TAG_FOLDER = "folder";
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700377 private static final String TAG_PARTNER_FOLDER = "partner-folder";
Winson Chungb3302ae2012-05-01 10:19:14 -0700378 private static final String TAG_EXTRA = "extra";
Daniel Sandler57dac262013-10-03 13:28:36 -0400379 private static final String TAG_INCLUDE = "include";
Winson Chung3d503fb2011-07-13 17:25:49 -0700380
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700381 private static final String ATTR_TITLE = "title";
382 private static final String ATTR_ICON = "icon";
383 private static final String ATTR_URI = "uri";
384 private static final String ATTR_PACKAGE_NAME = "packageName";
385 private static final String ATTR_CLASS_NAME = "className";
386
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800387 private final Context mContext;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700388 private final PackageManager mPackageManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700389 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700390 private long mMaxItemId = -1;
391 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800392
Winson Chung0b560dd2014-01-21 13:00:26 -0800393 private boolean mNewDbCreated = false;
394
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 DatabaseHelper(Context context) {
396 super(context, DATABASE_NAME, null, DATABASE_VERSION);
397 mContext = context;
Jeff Sharkey5aeef582014-04-14 13:26:42 -0700398 mPackageManager = context.getPackageManager();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700399 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700400
401 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
402 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700403 if (mMaxItemId == -1) {
404 mMaxItemId = initializeMaxItemId(getWritableDatabase());
405 }
406 if (mMaxScreenId == -1) {
407 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700408 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800409 }
410
Winson Chung0b560dd2014-01-21 13:00:26 -0800411 public boolean wasNewDbCreated() {
412 return mNewDbCreated;
413 }
414
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700415 /**
416 * Send notification that we've deleted the {@link AppWidgetHost},
417 * probably as part of the initial database creation. The receiver may
418 * want to re-call {@link AppWidgetHost#startListening()} to ensure
419 * callbacks are correctly set.
420 */
421 private void sendAppWidgetResetNotify() {
422 final ContentResolver resolver = mContext.getContentResolver();
423 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
424 }
425
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800426 @Override
427 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800428 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700429
Adam Cohendcd297f2013-06-18 13:13:40 -0700430 mMaxItemId = 1;
431 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800432 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700433
Kenny Guyed131872014-04-30 03:02:21 +0100434 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
435 long userSerialNumber = userManager.getSerialNumberForUser(
436 UserHandleCompat.myUserHandle());
437
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800438 db.execSQL("CREATE TABLE favorites (" +
439 "_id INTEGER PRIMARY KEY," +
440 "title TEXT," +
441 "intent TEXT," +
442 "container INTEGER," +
443 "screen INTEGER," +
444 "cellX INTEGER," +
445 "cellY INTEGER," +
446 "spanX INTEGER," +
447 "spanY INTEGER," +
448 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700449 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800450 "isShortcut INTEGER," +
451 "iconType INTEGER," +
452 "iconPackage TEXT," +
453 "iconResource TEXT," +
454 "icon BLOB," +
455 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400456 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400457 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500458 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100459 "restored INTEGER NOT NULL DEFAULT 0," +
460 "profileId INTEGER DEFAULT " + userSerialNumber +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800461 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700462 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800463
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700464 // Database was just created, so wipe any previous widgets
465 if (mAppWidgetHost != null) {
466 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700467 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700469
Adam Cohen6dbe0492013-12-02 17:00:14 -0800470 if (shouldImportLauncher2Database(mContext)) {
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500471 // Try converting the old database
472 ContentValuesCallback permuteScreensCb = new ContentValuesCallback() {
473 public void onRow(ContentValues values) {
474 int container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
475 if (container == Favorites.CONTAINER_DESKTOP) {
476 int screen = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
477 screen = (int) upgradeLauncherDb_permuteScreens(screen);
478 values.put(LauncherSettings.Favorites.SCREEN, screen);
479 }
480 }
481 };
482 Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
483 "/old_favorites?notify=true");
484 if (!convertDatabase(db, uri, permuteScreensCb, true)) {
485 // Try and upgrade from the Launcher2 db
Jason Monk0bfcceb2014-03-21 15:42:06 -0400486 uri = Uri.parse(mContext.getString(R.string.old_launcher_provider_uri));
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500487 if (!convertDatabase(db, uri, permuteScreensCb, false)) {
488 // If we fail, then set a flag to load the default workspace
489 setFlagEmptyDbCreated();
490 return;
Winson Chungc763c4e2013-07-19 13:49:06 -0700491 }
492 }
Dan Sandlerf0b8dac2013-11-19 12:21:25 -0500493 // Right now, in non-default workspace cases, we want to run the final
494 // upgrade code (ie. to fix workspace screen indices -> ids, etc.), so
495 // set that flag too.
496 setFlagJustLoadedOldDb();
497 } else {
498 // Fresh and clean launcher DB.
499 mMaxItemId = initializeMaxItemId(db);
500 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800501 }
502 }
503
Adam Cohendcd297f2013-06-18 13:13:40 -0700504 private void addWorkspacesTable(SQLiteDatabase db) {
505 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
506 LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400507 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
508 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700509 ");");
510 }
511
Adam Cohen119285e2014-04-02 16:59:08 -0700512 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700513 // Delete items directly on the workspace who's screen id doesn't exist
514 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
515 // AND container = -100"
516 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
517 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700518 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700519 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
520 " AND " +
521 LauncherSettings.Favorites.CONTAINER + " = " +
522 LauncherSettings.Favorites.CONTAINER_DESKTOP;
523 db.execSQL(removeOrphanedDesktopItems);
524
525 // Delete items contained in folders which no longer exist (after above statement)
526 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
527 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
528 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
529 " WHERE " +
530 LauncherSettings.Favorites.CONTAINER + " <> " +
531 LauncherSettings.Favorites.CONTAINER_DESKTOP +
532 " AND "
533 + LauncherSettings.Favorites.CONTAINER + " <> " +
534 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
535 " AND "
536 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
537 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
538 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
539 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
540 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700541 }
542
Winson Chungc763c4e2013-07-19 13:49:06 -0700543 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400544 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700545 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
546 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700547 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
548 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700549 editor.commit();
550 }
551
Winson Chungc763c4e2013-07-19 13:49:06 -0700552 private void setFlagEmptyDbCreated() {
553 String spKey = LauncherAppState.getSharedPreferencesKey();
554 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
555 SharedPreferences.Editor editor = sp.edit();
556 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
557 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
558 editor.commit();
559 }
560
561 // We rearrange the screens from the old launcher
562 // 12345 -> 34512
563 private long upgradeLauncherDb_permuteScreens(long screen) {
564 if (screen >= 2) {
565 return screen - 2;
566 } else {
567 return screen + 3;
568 }
569 }
570
571 private boolean convertDatabase(SQLiteDatabase db, Uri uri,
572 ContentValuesCallback cb, boolean deleteRows) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800573 if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 boolean converted = false;
575
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 final ContentResolver resolver = mContext.getContentResolver();
577 Cursor cursor = null;
578
579 try {
580 cursor = resolver.query(uri, null, null, null, null);
581 } catch (Exception e) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700582 // Ignore
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800583 }
584
585 // We already have a favorites database in the old provider
Winson Chungc763c4e2013-07-19 13:49:06 -0700586 if (cursor != null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587 try {
Winson Chungc763c4e2013-07-19 13:49:06 -0700588 if (cursor.getCount() > 0) {
589 converted = copyFromCursor(db, cursor, cb) > 0;
590 if (converted && deleteRows) {
591 resolver.delete(uri, null, null);
592 }
593 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800594 } finally {
595 cursor.close();
596 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700598
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 if (converted) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700600 // Convert widgets from this import into widgets
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800601 if (LOGD) Log.d(TAG, "converted and now triggering widget upgrade");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 convertWidgets(db);
Winson Chungc763c4e2013-07-19 13:49:06 -0700603
604 // Update max item id
605 mMaxItemId = initializeMaxItemId(db);
606 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
609 return converted;
610 }
611
Winson Chungc763c4e2013-07-19 13:49:06 -0700612 private int copyFromCursor(SQLiteDatabase db, Cursor c, ContentValuesCallback cb) {
Romain Guy73b979d2009-06-09 12:57:21 -0700613 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
615 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
616 final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
617 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
618 final int iconPackageIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
619 final int iconResourceIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
620 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
621 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
622 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
623 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
624 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
625 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
626 final int displayModeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
627
628 ContentValues[] rows = new ContentValues[c.getCount()];
629 int i = 0;
630 while (c.moveToNext()) {
631 ContentValues values = new ContentValues(c.getColumnCount());
Romain Guy73b979d2009-06-09 12:57:21 -0700632 values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
634 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
635 values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
636 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
637 values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
638 values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
639 values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
640 values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700641 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800642 values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
643 values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
644 values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
645 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
646 values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
Winson Chungc763c4e2013-07-19 13:49:06 -0700647 if (cb != null) {
648 cb.onRow(values);
649 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 rows[i++] = values;
651 }
652
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653 int total = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -0700654 if (i > 0) {
655 db.beginTransaction();
656 try {
657 int numValues = rows.length;
658 for (i = 0; i < numValues; i++) {
659 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
660 return 0;
661 } else {
662 total++;
663 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700665 db.setTransactionSuccessful();
666 } finally {
667 db.endTransaction();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800669 }
670
671 return total;
672 }
673
674 @Override
675 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700676 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700677
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 int version = oldVersion;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700679 if (version < 3) {
680 // upgrade 1,2 -> 3 added appWidgetId column
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 db.beginTransaction();
682 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700683 // Insert new column for holding appWidgetIds
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 db.execSQL("ALTER TABLE favorites " +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700685 "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800686 db.setTransactionSuccessful();
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700687 version = 3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688 } catch (SQLException ex) {
689 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800690 Log.e(TAG, ex.getMessage(), ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 } finally {
692 db.endTransaction();
693 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700694
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800695 // Convert existing widgets only if table upgrade was successful
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700696 if (version == 3) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 convertWidgets(db);
698 }
699 }
Romain Guy73b979d2009-06-09 12:57:21 -0700700
701 if (version < 4) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800702 version = 4;
Romain Guy73b979d2009-06-09 12:57:21 -0700703 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700704
Romain Guy509cd6a2010-03-23 15:10:56 -0700705 // Where's version 5?
706 // - Donut and sholes on 2.0 shipped with version 4 of launcher1.
Daniel Sandler325dc232013-06-05 22:57:57 -0400707 // - Passion shipped on 2.1 with version 6 of launcher3
Romain Guy509cd6a2010-03-23 15:10:56 -0700708 // - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher 1
709 // but version 5 on there was the updateContactsShortcuts change
710 // which was version 6 in launcher 2 (first shipped on passion 2.1r1).
711 // The updateContactsShortcuts change is idempotent, so running it twice
712 // is okay so we'll do that when upgrading the devices that shipped with it.
713 if (version < 6) {
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800714 // We went from 3 to 5 screens. Move everything 1 to the right
715 db.beginTransaction();
716 try {
717 db.execSQL("UPDATE favorites SET screen=(screen + 1);");
718 db.setTransactionSuccessful();
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800719 } catch (SQLException ex) {
720 // Old version remains, which means we wipe old data
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800721 Log.e(TAG, ex.getMessage(), ex);
Mike Cleron3a2b3f22009-11-05 17:17:42 -0800722 } finally {
723 db.endTransaction();
724 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700725
Romain Guy509cd6a2010-03-23 15:10:56 -0700726 // We added the fast track.
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800727 if (updateContactsShortcuts(db)) {
728 version = 6;
729 }
730 }
Bjorn Bringert7984c942009-12-09 15:38:25 +0000731
732 if (version < 7) {
733 // Version 7 gets rid of the special search widget.
734 convertWidgets(db);
735 version = 7;
736 }
737
Joe Onorato0589f0f2010-02-08 13:44:00 -0800738 if (version < 8) {
739 // Version 8 (froyo) has the icons all normalized. This should
740 // already be the case in practice, but we now rely on it and don't
741 // resample the images each time.
742 normalizeIcons(db);
743 version = 8;
744 }
745
Winson Chung3d503fb2011-07-13 17:25:49 -0700746 if (version < 9) {
747 // The max id is not yet set at this point (onUpgrade is triggered in the ctor
748 // 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 -0700749 if (mMaxItemId == -1) {
750 mMaxItemId = initializeMaxItemId(db);
Winson Chung3d503fb2011-07-13 17:25:49 -0700751 }
752
753 // Add default hotseat icons
Winson Chung6d092682011-11-16 18:43:26 -0800754 loadFavorites(db, R.xml.update_workspace);
Winson Chung3d503fb2011-07-13 17:25:49 -0700755 version = 9;
756 }
757
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700758 // We bumped the version three time during JB, once to update the launch flags, once to
759 // update the override for the default launch animation and once to set the mimetype
760 // to improve startup performance
761 if (version < 12) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700762 // Contact shortcuts need a different set of flags to be launched now
763 // The updateContactsShortcuts change is idempotent, so we can keep using it like
764 // back in the Donut days
765 updateContactsShortcuts(db);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700766 version = 12;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700767 }
768
Adam Cohendcd297f2013-06-18 13:13:40 -0700769 if (version < 13) {
770 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
771 // to persist workspace screens and their relative order.
772 mMaxScreenId = 0;
773
774 // This will never happen in the wild, but when we switch to using workspace
775 // screen ids, redo the import from old launcher.
Winson Chungc763c4e2013-07-19 13:49:06 -0700776 sJustLoadedFromOldDb = true;
Adam Cohendcd297f2013-06-18 13:13:40 -0700777
778 addWorkspacesTable(db);
779 version = 13;
780 }
781
Chris Wrend5e66bf2013-09-16 14:02:29 -0400782 if (version < 14) {
783 db.beginTransaction();
784 try {
785 // Insert new column for holding widget provider name
786 db.execSQL("ALTER TABLE favorites " +
787 "ADD COLUMN appWidgetProvider TEXT;");
788 db.setTransactionSuccessful();
789 version = 14;
790 } catch (SQLException ex) {
791 // Old version remains, which means we wipe old data
792 Log.e(TAG, ex.getMessage(), ex);
793 } finally {
794 db.endTransaction();
795 }
796 }
797
Chris Wren1ada10d2013-09-13 18:01:38 -0400798 if (version < 15) {
799 db.beginTransaction();
800 try {
801 // Insert new column for holding update timestamp
802 db.execSQL("ALTER TABLE favorites " +
803 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
804 db.execSQL("ALTER TABLE workspaceScreens " +
805 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
806 db.setTransactionSuccessful();
807 version = 15;
808 } catch (SQLException ex) {
809 // Old version remains, which means we wipe old data
810 Log.e(TAG, ex.getMessage(), ex);
811 } finally {
812 db.endTransaction();
813 }
814 }
815
Chris Wrenf4d08112014-01-16 18:13:56 -0500816
817 if (version < 16) {
818 db.beginTransaction();
819 try {
820 // Insert new column for holding restore status
821 db.execSQL("ALTER TABLE favorites " +
822 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
823 db.setTransactionSuccessful();
824 version = 16;
825 } catch (SQLException ex) {
826 // Old version remains, which means we wipe old data
827 Log.e(TAG, ex.getMessage(), ex);
828 } finally {
829 db.endTransaction();
830 }
831 }
832
Adam Cohen71e03b92014-02-21 14:09:53 -0800833 if (version < 17) {
834 // We use the db version upgrade here to identify users who may not have seen
835 // clings yet (because they weren't available), but for whom the clings are now
836 // available (tablet users). Because one of the possible cling flows (migration)
837 // is very destructive (wipes out workspaces), we want to prevent this from showing
838 // until clear data. We do so by marking that the clings have been shown.
839 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
840 version = 17;
841 }
842
Adam Cohen119285e2014-04-02 16:59:08 -0700843 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700844 // No-op
845 version = 18;
846 }
847
848 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700849 // Due to a data loss bug, some users may have items associated with screen ids
850 // which no longer exist. Since this can cause other problems, and since the user
851 // will never see these items anyway, we use database upgrade as an opportunity to
852 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700853 removeOrphanedItems(db);
854 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700855 }
856
Kenny Guyed131872014-04-30 03:02:21 +0100857 if (version < 20) {
858 // Add userId column
859 if (addProfileColumn(db)) {
860 version = 20;
861 }
862 // else old version remains, which means we wipe old data
863 }
864
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800865 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800866 Log.w(TAG, "Destroying all old data.");
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700868 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
869
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800870 onCreate(db);
871 }
872 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800873
Kenny Guyed131872014-04-30 03:02:21 +0100874 private boolean addProfileColumn(SQLiteDatabase db) {
875 db.beginTransaction();
876 try {
877 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
878 // Default to the serial number of this user, for older
879 // shortcuts.
880 long userSerialNumber = userManager.getSerialNumberForUser(
881 UserHandleCompat.myUserHandle());
882 // Insert new column for holding user serial number
883 db.execSQL("ALTER TABLE favorites " +
884 "ADD COLUMN profileId INTEGER DEFAULT "
885 + userSerialNumber + ";");
886 db.setTransactionSuccessful();
887 } catch (SQLException ex) {
888 // Old version remains, which means we wipe old data
889 Log.e(TAG, ex.getMessage(), ex);
890 return false;
891 } finally {
892 db.endTransaction();
893 }
894 return true;
895 }
896
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800897 private boolean updateContactsShortcuts(SQLiteDatabase db) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800898 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
899 new int[] { Favorites.ITEM_TYPE_SHORTCUT });
900
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700901 Cursor c = null;
902 final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800903 db.beginTransaction();
904 try {
905 // Select and iterate through each matching widget
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700906 c = db.query(TABLE_FAVORITES,
907 new String[] { Favorites._ID, Favorites.INTENT },
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800908 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700909 if (c == null) return false;
910
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800911 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700912
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800913 final int idIndex = c.getColumnIndex(Favorites._ID);
914 final int intentIndex = c.getColumnIndex(Favorites.INTENT);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700915
916 while (c.moveToNext()) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800917 long favoriteId = c.getLong(idIndex);
918 final String intentUri = c.getString(intentIndex);
919 if (intentUri != null) {
920 try {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700921 final Intent intent = Intent.parseUri(intentUri, 0);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800922 android.util.Log.d("Home", intent.toString());
923 final Uri uri = intent.getData();
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700924 if (uri != null) {
925 final String data = uri.toString();
926 if ((Intent.ACTION_VIEW.equals(intent.getAction()) ||
927 actionQuickContact.equals(intent.getAction())) &&
928 (data.startsWith("content://contacts/people/") ||
929 data.startsWith("content://com.android.contacts/" +
930 "contacts/lookup/"))) {
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800931
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700932 final Intent newIntent = new Intent(actionQuickContact);
933 // When starting from the launcher, start in a new, cleared task
934 // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
935 // clear the whole thing preemptively here since
936 // QuickContactActivity will finish itself when launching other
937 // detail activities.
938 newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
939 Intent.FLAG_ACTIVITY_CLEAR_TASK);
Winson Chung2672ff92012-05-04 16:22:30 -0700940 newIntent.putExtra(
941 Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700942 newIntent.setData(uri);
Daniel Lehmannd02402c2012-05-14 18:30:53 -0700943 // Determine the type and also put that in the shortcut
944 // (that can speed up launch a bit)
945 newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800946
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700947 final ContentValues values = new ContentValues();
948 values.put(LauncherSettings.Favorites.INTENT,
949 newIntent.toUri(0));
950
951 String updateWhere = Favorites._ID + "=" + favoriteId;
952 db.update(TABLE_FAVORITES, values, updateWhere, null);
953 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800954 }
955 } catch (RuntimeException ex) {
956 Log.e(TAG, "Problem upgrading shortcut", ex);
957 } catch (URISyntaxException e) {
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700958 Log.e(TAG, "Problem upgrading shortcut", e);
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800959 }
960 }
961 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700962
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800963 db.setTransactionSuccessful();
964 } catch (SQLException ex) {
965 Log.w(TAG, "Problem while upgrading contacts", ex);
966 return false;
967 } finally {
968 db.endTransaction();
969 if (c != null) {
970 c.close();
971 }
972 }
973
974 return true;
975 }
976
Joe Onorato0589f0f2010-02-08 13:44:00 -0800977 private void normalizeIcons(SQLiteDatabase db) {
978 Log.d(TAG, "normalizing icons");
979
Joe Onorato346e1292010-02-18 10:34:24 -0500980 db.beginTransaction();
Joe Onorato0589f0f2010-02-08 13:44:00 -0800981 Cursor c = null;
Joe Onorato9690b392010-03-23 17:34:37 -0400982 SQLiteStatement update = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800983 try {
984 boolean logged = false;
Joe Onorato9690b392010-03-23 17:34:37 -0400985 update = db.compileStatement("UPDATE favorites "
Jeff Hamiltoneaf77d62010-02-13 00:08:17 -0600986 + "SET icon=? WHERE _id=?");
Joe Onorato0589f0f2010-02-08 13:44:00 -0800987
988 c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType=" +
989 Favorites.ICON_TYPE_BITMAP, null);
990
991 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
992 final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
993
994 while (c.moveToNext()) {
995 long id = c.getLong(idIndex);
996 byte[] data = c.getBlob(iconIndex);
997 try {
998 Bitmap bitmap = Utilities.resampleIconBitmap(
999 BitmapFactory.decodeByteArray(data, 0, data.length),
1000 mContext);
1001 if (bitmap != null) {
1002 update.bindLong(1, id);
1003 data = ItemInfo.flattenBitmap(bitmap);
1004 if (data != null) {
1005 update.bindBlob(2, data);
1006 update.execute();
1007 }
1008 bitmap.recycle();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001009 }
1010 } catch (Exception e) {
1011 if (!logged) {
1012 Log.e(TAG, "Failed normalizing icon " + id, e);
1013 } else {
1014 Log.e(TAG, "Also failed normalizing icon " + id);
1015 }
1016 logged = true;
1017 }
1018 }
Bjorn Bringert3a928e42010-02-19 11:15:40 +00001019 db.setTransactionSuccessful();
Joe Onorato0589f0f2010-02-08 13:44:00 -08001020 } catch (SQLException ex) {
1021 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
1022 } finally {
1023 db.endTransaction();
Joe Onorato9690b392010-03-23 17:34:37 -04001024 if (update != null) {
1025 update.close();
1026 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08001027 if (c != null) {
1028 c.close();
1029 }
1030 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001031 }
1032
1033 // Generates a new ID to use for an object in your database. This method should be only
1034 // called from the main UI thread. As an exception, we do call it when we call the
1035 // constructor from the worker thread; however, this doesn't extend until after the
1036 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1037 // after that point
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 public long generateNewItemId() {
1039 if (mMaxItemId < 0) {
1040 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001041 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001042 mMaxItemId += 1;
1043 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 }
1045
Winson Chungc763c4e2013-07-19 13:49:06 -07001046 public void updateMaxItemId(long id) {
1047 mMaxItemId = id + 1;
1048 }
1049
Chris Wren5dee7af2013-12-20 17:22:11 -05001050 public void checkId(String table, ContentValues values) {
1051 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
1052 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
1053 mMaxScreenId = Math.max(id, mMaxScreenId);
1054 } else {
1055 mMaxItemId = Math.max(id, mMaxItemId);
1056 }
1057 }
1058
Adam Cohendcd297f2013-06-18 13:13:40 -07001059 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001060 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
1061
1062 // get the result
1063 final int maxIdIndex = 0;
1064 long id = -1;
1065 if (c != null && c.moveToNext()) {
1066 id = c.getLong(maxIdIndex);
1067 }
Michael Jurka5130e402011-10-13 04:55:35 -07001068 if (c != null) {
1069 c.close();
1070 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001071
1072 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001073 throw new RuntimeException("Error: could not query max item id");
1074 }
1075
1076 return id;
1077 }
1078
1079 // Generates a new ID to use for an workspace screen in your database. This method
1080 // should be only called from the main UI thread. As an exception, we do call it when we
1081 // call the constructor from the worker thread; however, this doesn't extend until after the
1082 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1083 // after that point
1084 public long generateNewScreenId() {
1085 if (mMaxScreenId < 0) {
1086 throw new RuntimeException("Error: max screen id was not initialized");
1087 }
1088 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -08001089 // Log to disk
1090 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001091 return mMaxScreenId;
1092 }
1093
1094 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -08001095 // Log to disk
1096 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -07001097 mMaxScreenId = maxScreenId;
1098 }
1099
1100 private long initializeMaxScreenId(SQLiteDatabase db) {
1101 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1102
1103 // get the result
1104 final int maxIdIndex = 0;
1105 long id = -1;
1106 if (c != null && c.moveToNext()) {
1107 id = c.getLong(maxIdIndex);
1108 }
1109 if (c != null) {
1110 c.close();
1111 }
1112
1113 if (id == -1) {
1114 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001115 }
1116
Winson Chunga90303b2013-11-15 13:05:06 -08001117 // Log to disk
1118 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001119 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -08001120 }
1121
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001122 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001123 * Upgrade existing clock and photo frame widgets into their new widget
Bjorn Bringert93c45762009-12-16 13:19:47 +00001124 * equivalents.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001125 */
1126 private void convertWidgets(SQLiteDatabase db) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001127 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001128 final int[] bindSources = new int[] {
1129 Favorites.ITEM_TYPE_WIDGET_CLOCK,
1130 Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME,
Bjorn Bringert7984c942009-12-09 15:38:25 +00001131 Favorites.ITEM_TYPE_WIDGET_SEARCH,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001132 };
Bjorn Bringert7984c942009-12-09 15:38:25 +00001133
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001135
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 Cursor c = null;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 db.beginTransaction();
1139 try {
1140 // Select and iterate through each matching widget
Bjorn Bringert7984c942009-12-09 15:38:25 +00001141 c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001142 selectWhere, null, null, null, null);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001143
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001144 if (LOGD) Log.d(TAG, "found upgrade cursor count=" + c.getCount());
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001145
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001146 final ContentValues values = new ContentValues();
1147 while (c != null && c.moveToNext()) {
1148 long favoriteId = c.getLong(0);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001149 int favoriteType = c.getInt(1);
1150
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001151 // Allocate and update database with new appWidgetId
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001152 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001153 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001154
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001155 if (LOGD) {
1156 Log.d(TAG, "allocated appWidgetId=" + appWidgetId
1157 + " for favoriteId=" + favoriteId);
1158 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001159 values.clear();
Bjorn Bringert7984c942009-12-09 15:38:25 +00001160 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
1161 values.put(Favorites.APPWIDGET_ID, appWidgetId);
1162
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001163 // Original widgets might not have valid spans when upgrading
Bjorn Bringert7984c942009-12-09 15:38:25 +00001164 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
1165 values.put(LauncherSettings.Favorites.SPANX, 4);
1166 values.put(LauncherSettings.Favorites.SPANY, 1);
1167 } else {
1168 values.put(LauncherSettings.Favorites.SPANX, 2);
1169 values.put(LauncherSettings.Favorites.SPANY, 2);
1170 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171
1172 String updateWhere = Favorites._ID + "=" + favoriteId;
1173 db.update(TABLE_FAVORITES, values, updateWhere, null);
Bjorn Bringert34251342009-12-15 13:33:11 +00001174
Bjorn Bringert34251342009-12-15 13:33:11 +00001175 if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001176 // TODO: check return value
1177 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001178 new ComponentName("com.android.alarmclock",
1179 "com.android.alarmclock.AnalogAppWidgetProvider"));
1180 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001181 // TODO: check return value
1182 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringert34251342009-12-15 13:33:11 +00001183 new ComponentName("com.android.camera",
1184 "com.android.camera.PhotoAppWidgetProvider"));
1185 } else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001186 // TODO: check return value
1187 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001188 getSearchWidgetProvider());
Bjorn Bringert34251342009-12-15 13:33:11 +00001189 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001190 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001191 Log.e(TAG, "Problem allocating appWidgetId", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001192 }
1193 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001194
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001195 db.setTransactionSuccessful();
1196 } catch (SQLException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001197 Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001198 } finally {
1199 db.endTransaction();
1200 if (c != null) {
1201 c.close();
1202 }
1203 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001204
1205 // Update max item id
1206 mMaxItemId = initializeMaxItemId(db);
1207 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001208 }
1209
Michael Jurka8b805b12012-04-18 14:23:14 -07001210 private static final void beginDocument(XmlPullParser parser, String firstElementName)
1211 throws XmlPullParserException, IOException {
1212 int type;
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001213 while ((type = parser.next()) != XmlPullParser.START_TAG
1214 && type != XmlPullParser.END_DOCUMENT) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001215 ;
1216 }
1217
Michael Jurka9bc8eba2012-05-21 20:36:44 -07001218 if (type != XmlPullParser.START_TAG) {
Michael Jurka8b805b12012-04-18 14:23:14 -07001219 throw new XmlPullParserException("No start tag found");
1220 }
1221
1222 if (!parser.getName().equals(firstElementName)) {
1223 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
1224 ", expected " + firstElementName);
1225 }
1226 }
1227
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001228 private static Intent buildMainIntent() {
1229 Intent intent = new Intent(Intent.ACTION_MAIN, null);
1230 intent.addCategory(Intent.CATEGORY_LAUNCHER);
1231 return intent;
1232 }
1233
Adam Cohen71483f42014-05-15 14:04:01 -07001234 private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
1235 ArrayList<Long> screenIds = new ArrayList<Long>();
1236 int count = loadFavoritesRecursive(db, workspaceResourceId, screenIds);
1237
1238 // Add the screens specified by the items above
1239 Collections.sort(screenIds);
1240 int rank = 0;
1241 ContentValues values = new ContentValues();
1242 for (Long id : screenIds) {
1243 values.clear();
1244 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1245 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1246 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1247 throw new RuntimeException("Failed initialize screen table"
1248 + "from default layout");
1249 }
1250 rank++;
1251 }
1252
1253 // Ensure that the max ids are initialized
1254 mMaxItemId = initializeMaxItemId(db);
1255 mMaxScreenId = initializeMaxScreenId(db);
1256 return count;
1257 }
1258
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001259 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001260 * Loads the default set of favorite packages from an xml file.
1261 *
1262 * @param db The database to write the values into
Winson Chung3d503fb2011-07-13 17:25:49 -07001263 * @param filterContainerId The specific container id of items to load
Adam Cohen71483f42014-05-15 14:04:01 -07001264 * @param the set of screenIds which are used by the favorites
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001265 */
Adam Cohen71483f42014-05-15 14:04:01 -07001266 private int loadFavoritesRecursive(SQLiteDatabase db, int workspaceResourceId,
1267 ArrayList<Long> screenIds) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001268
Adam Cohen71483f42014-05-15 14:04:01 -07001269
1270
1271 ContentValues values = new ContentValues();
Daniel Sandler57dac262013-10-03 13:28:36 -04001272 if (LOGD) Log.v(TAG, String.format("Loading favorites from resid=0x%08x", workspaceResourceId));
1273
Adam Cohen71483f42014-05-15 14:04:01 -07001274 int count = 0;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001275 try {
Winson Chung6d092682011-11-16 18:43:26 -08001276 XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001277 AttributeSet attrs = Xml.asAttributeSet(parser);
Michael Jurka8b805b12012-04-18 14:23:14 -07001278 beginDocument(parser, TAG_FAVORITES);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001279
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001280 final int depth = parser.getDepth();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001281
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001282 int type;
1283 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1284 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1285
1286 if (type != XmlPullParser.START_TAG) {
1287 continue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001288 }
1289
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001290 boolean added = false;
1291 final String name = parser.getName();
1292
Daniel Sandler57dac262013-10-03 13:28:36 -04001293 if (TAG_INCLUDE.equals(name)) {
1294 final TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Include);
1295
1296 final int resId = a.getResourceId(R.styleable.Include_workspace, 0);
1297
1298 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s<include workspace=%08x>"),
1299 "", resId));
1300
1301 if (resId != 0 && resId != workspaceResourceId) {
1302 // recursively load some more favorites, why not?
Adam Cohen71483f42014-05-15 14:04:01 -07001303 count += loadFavoritesRecursive(db, resId, screenIds);
Daniel Sandler57dac262013-10-03 13:28:36 -04001304 added = false;
Daniel Sandler57dac262013-10-03 13:28:36 -04001305 } else {
1306 Log.w(TAG, String.format("Skipping <include workspace=0x%08x>", resId));
1307 }
1308
1309 a.recycle();
1310
1311 if (LOGD) Log.v(TAG, String.format(("%" + (2*(depth+1)) + "s</include>"), ""));
1312 continue;
1313 }
1314
1315 // Assuming it's a <favorite> at this point
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001316 TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
1317
Winson Chung3d503fb2011-07-13 17:25:49 -07001318 long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1319 if (a.hasValue(R.styleable.Favorite_container)) {
1320 container = Long.valueOf(a.getString(R.styleable.Favorite_container));
1321 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001322
Winson Chung6d092682011-11-16 18:43:26 -08001323 String screen = a.getString(R.styleable.Favorite_screen);
1324 String x = a.getString(R.styleable.Favorite_x);
1325 String y = a.getString(R.styleable.Favorite_y);
1326
Winson Chung6d092682011-11-16 18:43:26 -08001327 values.clear();
1328 values.put(LauncherSettings.Favorites.CONTAINER, container);
1329 values.put(LauncherSettings.Favorites.SCREEN, screen);
1330 values.put(LauncherSettings.Favorites.CELLX, x);
1331 values.put(LauncherSettings.Favorites.CELLY, y);
1332
Daniel Sandler57dac262013-10-03 13:28:36 -04001333 if (LOGD) {
1334 final String title = a.getString(R.styleable.Favorite_title);
1335 final String pkg = a.getString(R.styleable.Favorite_packageName);
1336 final String something = title != null ? title : pkg;
1337 Log.v(TAG, String.format(
1338 ("%" + (2*(depth+1)) + "s<%s%s c=%d s=%s x=%s y=%s>"),
1339 "", name,
1340 (something == null ? "" : (" \"" + something + "\"")),
1341 container, screen, x, y));
1342 }
1343
Winson Chung6d092682011-11-16 18:43:26 -08001344 if (TAG_FAVORITE.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001345 long id = addAppShortcut(db, values, parser);
Winson Chung6d092682011-11-16 18:43:26 -08001346 added = id >= 0;
1347 } else if (TAG_SEARCH.equals(name)) {
1348 added = addSearchWidget(db, values);
1349 } else if (TAG_CLOCK.equals(name)) {
1350 added = addClockWidget(db, values);
1351 } else if (TAG_APPWIDGET.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001352 added = addAppWidget(parser, attrs, type, db, values, a);
Winson Chung6d092682011-11-16 18:43:26 -08001353 } else if (TAG_SHORTCUT.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001354 long id = addUriShortcut(db, values, mContext.getResources(), parser);
Winson Chung6d092682011-11-16 18:43:26 -08001355 added = id >= 0;
Jason Monk41314972014-03-03 16:11:30 -05001356 } else if (TAG_RESOLVE.equals(name)) {
1357 // This looks through the contained favorites (or meta-favorites) and
1358 // attempts to add them as shortcuts in the fallback group's location
1359 // until one is added successfully.
1360 added = false;
1361 final int groupDepth = parser.getDepth();
1362 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1363 parser.getDepth() > groupDepth) {
1364 if (type != XmlPullParser.START_TAG) {
1365 continue;
1366 }
1367 final String fallback_item_name = parser.getName();
1368 final TypedArray ar = mContext.obtainStyledAttributes(attrs,
1369 R.styleable.Favorite);
1370 if (!added) {
1371 if (TAG_FAVORITE.equals(fallback_item_name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001372 final long id = addAppShortcut(db, values, parser);
Jason Monk41314972014-03-03 16:11:30 -05001373 added = id >= 0;
1374 } else {
1375 Log.e(TAG, "Fallback groups can contain only favorites "
1376 + ar.toString());
1377 }
1378 }
1379 ar.recycle();
1380 }
Winson Chung6d092682011-11-16 18:43:26 -08001381 } else if (TAG_FOLDER.equals(name)) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001382 // Folder contents are nested in this XML file
1383 added = loadFolder(db, values, mContext.getResources(), parser);
Winson Chung3d503fb2011-07-13 17:25:49 -07001384
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001385 } else if (TAG_PARTNER_FOLDER.equals(name)) {
1386 // Folder contents come from an external XML resource
1387 final Partner partner = Partner.get(mPackageManager);
1388 if (partner != null) {
1389 final Resources partnerRes = partner.getResources();
1390 final int resId = partnerRes.getIdentifier(Partner.RESOURCE_FOLDER,
1391 "xml", partner.getPackageName());
1392 if (resId != 0) {
1393 final XmlResourceParser partnerParser = partnerRes.getXml(resId);
1394 beginDocument(partnerParser, TAG_FOLDER);
1395 added = loadFolder(db, values, partnerRes, partnerParser);
Winson Chung6d092682011-11-16 18:43:26 -08001396 }
Winson Chung3d503fb2011-07-13 17:25:49 -07001397 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001398 }
Adam Cohen71483f42014-05-15 14:04:01 -07001399 if (added) {
1400 long screenId = Long.parseLong(screen);
1401 // Keep track of the set of screens which need to be added to the db.
1402 if (!screenIds.contains(screenId) &&
1403 container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1404 screenIds.add(screenId);
1405 }
1406 count++;
1407 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001408 a.recycle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001409 }
1410 } catch (XmlPullParserException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001411 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001412 } catch (IOException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001413 Log.w(TAG, "Got exception parsing favorites.", e);
Winson Chung3d503fb2011-07-13 17:25:49 -07001414 } catch (RuntimeException e) {
1415 Log.w(TAG, "Got exception parsing favorites.", e);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001416 }
Adam Cohen71483f42014-05-15 14:04:01 -07001417 return count;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001418 }
1419
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001420 /**
1421 * Parse folder starting at current {@link XmlPullParser} location.
1422 */
1423 private boolean loadFolder(SQLiteDatabase db, ContentValues values, Resources res,
1424 XmlResourceParser parser) throws IOException, XmlPullParserException {
1425 final String title;
1426 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
1427 if (titleResId != 0) {
1428 title = res.getString(titleResId);
1429 } else {
1430 title = mContext.getResources().getString(R.string.folder_name);
1431 }
1432
1433 values.put(LauncherSettings.Favorites.TITLE, title);
1434 long folderId = addFolder(db, values);
1435 boolean added = folderId >= 0;
1436
1437 ArrayList<Long> folderItems = new ArrayList<Long>();
1438
1439 int type;
1440 int folderDepth = parser.getDepth();
1441 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1442 parser.getDepth() > folderDepth) {
1443 if (type != XmlPullParser.START_TAG) {
1444 continue;
1445 }
1446 final String tag = parser.getName();
1447
1448 final ContentValues childValues = new ContentValues();
1449 childValues.put(LauncherSettings.Favorites.CONTAINER, folderId);
1450
1451 if (LOGD) {
1452 final String pkg = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1453 final String uri = getAttributeValue(parser, ATTR_URI);
1454 Log.v(TAG, String.format(("%" + (2*(folderDepth+1)) + "s<%s \"%s\">"), "",
1455 tag, uri != null ? uri : pkg));
1456 }
1457
1458 if (TAG_FAVORITE.equals(tag) && folderId >= 0) {
1459 final long id = addAppShortcut(db, childValues, parser);
1460 if (id >= 0) {
1461 folderItems.add(id);
1462 }
1463 } else if (TAG_SHORTCUT.equals(tag) && folderId >= 0) {
1464 final long id = addUriShortcut(db, childValues, res, parser);
1465 if (id >= 0) {
1466 folderItems.add(id);
1467 }
1468 } else {
1469 throw new RuntimeException("Folders can contain only shortcuts");
1470 }
1471 }
1472
1473 // We can only have folders with >= 2 items, so we need to remove the
1474 // folder and clean up if less than 2 items were included, or some
1475 // failed to add, and less than 2 were actually added
1476 if (folderItems.size() < 2 && folderId >= 0) {
1477 // Delete the folder
1478 deleteId(db, folderId);
1479
1480 // If we have a single item, promote it to where the folder
1481 // would have been.
1482 if (folderItems.size() == 1) {
1483 final ContentValues childValues = new ContentValues();
1484 copyInteger(values, childValues, LauncherSettings.Favorites.CONTAINER);
1485 copyInteger(values, childValues, LauncherSettings.Favorites.SCREEN);
1486 copyInteger(values, childValues, LauncherSettings.Favorites.CELLX);
1487 copyInteger(values, childValues, LauncherSettings.Favorites.CELLY);
1488
1489 final long id = folderItems.get(0);
1490 db.update(TABLE_FAVORITES, childValues,
1491 LauncherSettings.Favorites._ID + "=" + id, null);
1492 } else {
1493 added = false;
1494 }
1495 }
1496 return added;
1497 }
1498
Jason Monk41314972014-03-03 16:11:30 -05001499 // A meta shortcut attempts to resolve an intent specified as a URI in the XML, if a
1500 // logical choice for what shortcut should be used for that intent exists, then it is
1501 // added. Otherwise add nothing.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001502 private long addAppShortcutByUri(SQLiteDatabase db, ContentValues values,
1503 String intentUri) {
Jason Monk41314972014-03-03 16:11:30 -05001504 Intent metaIntent;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001505 try {
Jason Monk41314972014-03-03 16:11:30 -05001506 metaIntent = Intent.parseUri(intentUri, 0);
1507 } catch (URISyntaxException e) {
1508 Log.e(TAG, "Unable to add meta-favorite: " + intentUri, e);
1509 return -1;
1510 }
1511
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001512 ResolveInfo resolved = mPackageManager.resolveActivity(metaIntent,
Jason Monk41314972014-03-03 16:11:30 -05001513 PackageManager.MATCH_DEFAULT_ONLY);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001514 final List<ResolveInfo> appList = mPackageManager.queryIntentActivities(
Jason Monk41314972014-03-03 16:11:30 -05001515 metaIntent, PackageManager.MATCH_DEFAULT_ONLY);
1516
1517 // Verify that the result is an app and not just the resolver dialog asking which
1518 // app to use.
1519 if (wouldLaunchResolverActivity(resolved, appList)) {
1520 // If only one of the results is a system app then choose that as the default.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001521 final ResolveInfo systemApp = getSingleSystemActivity(appList);
Jason Monk41314972014-03-03 16:11:30 -05001522 if (systemApp == null) {
1523 // There is no logical choice for this meta-favorite, so rather than making
1524 // a bad choice just add nothing.
1525 Log.w(TAG, "No preference or single system activity found for "
1526 + metaIntent.toString());
Adam Cohen228da5a2011-07-27 22:23:47 -07001527 return -1;
1528 }
Jason Monk41314972014-03-03 16:11:30 -05001529 resolved = systemApp;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001530 }
Jason Monk41314972014-03-03 16:11:30 -05001531 final ActivityInfo info = resolved.activityInfo;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001532 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001533 intent.setComponent(new ComponentName(info.packageName, info.name));
1534 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1535 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1536
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001537 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(), intent);
Jason Monk41314972014-03-03 16:11:30 -05001538 }
1539
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001540 private ResolveInfo getSingleSystemActivity(List<ResolveInfo> appList) {
Jason Monk41314972014-03-03 16:11:30 -05001541 ResolveInfo systemResolve = null;
1542 final int N = appList.size();
1543 for (int i = 0; i < N; ++i) {
1544 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001545 ApplicationInfo info = mPackageManager.getApplicationInfo(
Jason Monk41314972014-03-03 16:11:30 -05001546 appList.get(i).activityInfo.packageName, 0);
1547 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1548 if (systemResolve != null) {
1549 return null;
1550 } else {
1551 systemResolve = appList.get(i);
1552 }
1553 }
1554 } catch (PackageManager.NameNotFoundException e) {
1555 Log.w(TAG, "Unable to get info about resolve results", e);
1556 return null;
1557 }
1558 }
1559 return systemResolve;
1560 }
1561
1562 private boolean wouldLaunchResolverActivity(ResolveInfo resolved,
1563 List<ResolveInfo> appList) {
1564 // If the list contains the above resolved activity, then it can't be
1565 // ResolverActivity itself.
1566 for (int i = 0; i < appList.size(); ++i) {
1567 ResolveInfo tmp = appList.get(i);
1568 if (tmp.activityInfo.name.equals(resolved.activityInfo.name)
1569 && tmp.activityInfo.packageName.equals(resolved.activityInfo.packageName)) {
1570 return false;
1571 }
1572 }
1573 return true;
1574 }
1575
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001576 private long addAppShortcut(SQLiteDatabase db, ContentValues values,
1577 XmlResourceParser parser) {
1578 final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
1579 final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
1580 final String uri = getAttributeValue(parser, ATTR_URI);
1581
1582 if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
Jason Monk41314972014-03-03 16:11:30 -05001583 ActivityInfo info;
Jason Monk41314972014-03-03 16:11:30 -05001584 try {
1585 ComponentName cn;
1586 try {
1587 cn = new ComponentName(packageName, className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001588 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001589 } catch (PackageManager.NameNotFoundException nnfe) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001590 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Jason Monk41314972014-03-03 16:11:30 -05001591 new String[] { packageName });
1592 cn = new ComponentName(packages[0], className);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001593 info = mPackageManager.getActivityInfo(cn, 0);
Jason Monk41314972014-03-03 16:11:30 -05001594 }
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001595 final Intent intent = buildMainIntent();
Jason Monk41314972014-03-03 16:11:30 -05001596 intent.setComponent(cn);
1597 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1598 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1599
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001600 return addAppShortcut(db, values, info.loadLabel(mPackageManager).toString(),
Jason Monk41314972014-03-03 16:11:30 -05001601 intent);
1602 } catch (PackageManager.NameNotFoundException e) {
1603 Log.w(TAG, "Unable to add favorite: " + packageName +
1604 "/" + className, e);
1605 }
1606 return -1;
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001607 } else if (!TextUtils.isEmpty(uri)) {
Jason Monk41314972014-03-03 16:11:30 -05001608 // If no component specified try to find a shortcut to add from the URI.
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001609 return addAppShortcutByUri(db, values, uri);
Jason Monk41314972014-03-03 16:11:30 -05001610 } else {
1611 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
1612 return -1;
1613 }
1614 }
1615
1616 private long addAppShortcut(SQLiteDatabase db, ContentValues values, String title,
1617 Intent intent) {
1618 long id = generateNewItemId();
1619 values.put(Favorites.INTENT, intent.toUri(0));
1620 values.put(Favorites.TITLE, title);
1621 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
1622 values.put(Favorites.SPANX, 1);
1623 values.put(Favorites.SPANY, 1);
1624 values.put(Favorites._ID, id);
1625 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1626 return -1;
1627 } else {
1628 return id;
1629 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001630 }
1631
1632 private long addFolder(SQLiteDatabase db, ContentValues values) {
1633 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
1634 values.put(Favorites.SPANX, 1);
1635 values.put(Favorites.SPANY, 1);
Adam Cohendcd297f2013-06-18 13:13:40 -07001636 long id = generateNewItemId();
Adam Cohen228da5a2011-07-27 22:23:47 -07001637 values.put(Favorites._ID, id);
1638 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
1639 return -1;
1640 } else {
1641 return id;
1642 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001643 }
1644
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001645 private ComponentName getSearchWidgetProvider() {
1646 SearchManager searchManager =
1647 (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
1648 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
1649 if (searchComponent == null) return null;
1650 return getProviderInPackage(searchComponent.getPackageName());
1651 }
1652
1653 /**
1654 * Gets an appwidget provider from the given package. If the package contains more than
1655 * one appwidget provider, an arbitrary one is returned.
1656 */
1657 private ComponentName getProviderInPackage(String packageName) {
1658 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1659 List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
1660 if (providers == null) return null;
1661 final int providerCount = providers.size();
1662 for (int i = 0; i < providerCount; i++) {
1663 ComponentName provider = providers.get(i).provider;
1664 if (provider != null && provider.getPackageName().equals(packageName)) {
1665 return provider;
1666 }
1667 }
1668 return null;
1669 }
1670
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001671 private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringertcd8fec02010-01-14 13:26:43 +00001672 ComponentName cn = getSearchWidgetProvider();
Winson Chungb3302ae2012-05-01 10:19:14 -07001673 return addAppWidget(db, values, cn, 4, 1, null);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001674 }
1675
1676 private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
Bjorn Bringert34251342009-12-15 13:33:11 +00001677 ComponentName cn = new ComponentName("com.android.alarmclock",
1678 "com.android.alarmclock.AnalogAppWidgetProvider");
Winson Chungb3302ae2012-05-01 10:19:14 -07001679 return addAppWidget(db, values, cn, 2, 2, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001680 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001681
Winson Chungb3302ae2012-05-01 10:19:14 -07001682 private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001683 SQLiteDatabase db, ContentValues values, TypedArray a)
1684 throws XmlPullParserException, IOException {
Romain Guy693599f2010-03-23 10:58:18 -07001685
Mike Cleronb87bd162009-10-30 16:36:56 -07001686 String packageName = a.getString(R.styleable.Favorite_packageName);
1687 String className = a.getString(R.styleable.Favorite_className);
1688
1689 if (packageName == null || className == null) {
1690 return false;
1691 }
Romain Guy693599f2010-03-23 10:58:18 -07001692
1693 boolean hasPackage = true;
Mike Cleronb87bd162009-10-30 16:36:56 -07001694 ComponentName cn = new ComponentName(packageName, className);
Romain Guy693599f2010-03-23 10:58:18 -07001695 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001696 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001697 } catch (Exception e) {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001698 String[] packages = mPackageManager.currentToCanonicalPackageNames(
Romain Guy693599f2010-03-23 10:58:18 -07001699 new String[] { packageName });
1700 cn = new ComponentName(packages[0], className);
1701 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001702 mPackageManager.getReceiverInfo(cn, 0);
Romain Guy693599f2010-03-23 10:58:18 -07001703 } catch (Exception e1) {
1704 hasPackage = false;
1705 }
1706 }
1707
1708 if (hasPackage) {
1709 int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
1710 int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
Winson Chungb3302ae2012-05-01 10:19:14 -07001711
1712 // Read the extras
1713 Bundle extras = new Bundle();
1714 int widgetDepth = parser.getDepth();
1715 while ((type = parser.next()) != XmlPullParser.END_TAG ||
1716 parser.getDepth() > widgetDepth) {
1717 if (type != XmlPullParser.START_TAG) {
1718 continue;
1719 }
1720
1721 TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
1722 if (TAG_EXTRA.equals(parser.getName())) {
1723 String key = ar.getString(R.styleable.Extra_key);
1724 String value = ar.getString(R.styleable.Extra_value);
1725 if (key != null && value != null) {
1726 extras.putString(key, value);
1727 } else {
1728 throw new RuntimeException("Widget extras must have a key and value");
1729 }
1730 } else {
1731 throw new RuntimeException("Widgets can contain only extras");
1732 }
1733 ar.recycle();
1734 }
1735
1736 return addAppWidget(db, values, cn, spanX, spanY, extras);
Romain Guy693599f2010-03-23 10:58:18 -07001737 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001738
Romain Guy693599f2010-03-23 10:58:18 -07001739 return false;
Bjorn Bringert7984c942009-12-09 15:38:25 +00001740 }
Bjorn Bringert7984c942009-12-09 15:38:25 +00001741 private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
Winson Chungb3302ae2012-05-01 10:19:14 -07001742 int spanX, int spanY, Bundle extras) {
Mike Cleronb87bd162009-10-30 16:36:56 -07001743 boolean allocatedAppWidgets = false;
1744 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1745
1746 try {
1747 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001748
Mike Cleronb87bd162009-10-30 16:36:56 -07001749 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
Bjorn Bringert7984c942009-12-09 15:38:25 +00001750 values.put(Favorites.SPANX, spanX);
1751 values.put(Favorites.SPANY, spanY);
Mike Cleronb87bd162009-10-30 16:36:56 -07001752 values.put(Favorites.APPWIDGET_ID, appWidgetId);
Chris Wrend5e66bf2013-09-16 14:02:29 -04001753 values.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 values.put(Favorites._ID, generateNewItemId());
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001755 dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
Mike Cleronb87bd162009-10-30 16:36:56 -07001756
1757 allocatedAppWidgets = true;
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001758
Michael Jurka8b805b12012-04-18 14:23:14 -07001759 // TODO: need to check return value
1760 appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
Winson Chungb3302ae2012-05-01 10:19:14 -07001761
1762 // Send a broadcast to configure the widget
1763 if (extras != null && !extras.isEmpty()) {
1764 Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
1765 intent.setComponent(cn);
1766 intent.putExtras(extras);
1767 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1768 mContext.sendBroadcast(intent);
1769 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001770 } catch (RuntimeException ex) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001771 Log.e(TAG, "Problem allocating appWidgetId", ex);
Mike Cleronb87bd162009-10-30 16:36:56 -07001772 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001773
Mike Cleronb87bd162009-10-30 16:36:56 -07001774 return allocatedAppWidgets;
1775 }
Adam Cohen228da5a2011-07-27 22:23:47 -07001776
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001777 private long addUriShortcut(SQLiteDatabase db, ContentValues values, Resources res,
1778 XmlResourceParser parser) {
1779 final int iconResId = getAttributeResourceValue(parser, ATTR_ICON, 0);
1780 final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
Mike Cleronb87bd162009-10-30 16:36:56 -07001781
Romain Guy7eb9e5e2009-12-02 20:10:07 -08001782 Intent intent;
Mike Cleronb87bd162009-10-30 16:36:56 -07001783 String uri = null;
1784 try {
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001785 uri = getAttributeValue(parser, ATTR_URI);
Mike Cleronb87bd162009-10-30 16:36:56 -07001786 intent = Intent.parseUri(uri, 0);
1787 } catch (URISyntaxException e) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001788 Log.w(TAG, "Shortcut has malformed uri: " + uri);
Adam Cohen228da5a2011-07-27 22:23:47 -07001789 return -1; // Oh well
Mike Cleronb87bd162009-10-30 16:36:56 -07001790 }
1791
1792 if (iconResId == 0 || titleResId == 0) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -08001793 Log.w(TAG, "Shortcut is missing title or icon resource ID");
Adam Cohen228da5a2011-07-27 22:23:47 -07001794 return -1;
Mike Cleronb87bd162009-10-30 16:36:56 -07001795 }
1796
Adam Cohendcd297f2013-06-18 13:13:40 -07001797 long id = generateNewItemId();
Mike Cleronb87bd162009-10-30 16:36:56 -07001798 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1799 values.put(Favorites.INTENT, intent.toUri(0));
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001800 values.put(Favorites.TITLE, res.getString(titleResId));
Mike Cleronb87bd162009-10-30 16:36:56 -07001801 values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
1802 values.put(Favorites.SPANX, 1);
1803 values.put(Favorites.SPANY, 1);
1804 values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
Jeff Sharkey5aeef582014-04-14 13:26:42 -07001805 values.put(Favorites.ICON_PACKAGE, res.getResourcePackageName(iconResId));
1806 values.put(Favorites.ICON_RESOURCE, res.getResourceName(iconResId));
Adam Cohen228da5a2011-07-27 22:23:47 -07001807 values.put(Favorites._ID, id);
Mike Cleronb87bd162009-10-30 16:36:56 -07001808
Adam Cohen228da5a2011-07-27 22:23:47 -07001809 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
1810 return -1;
1811 }
1812 return id;
Mike Cleronb87bd162009-10-30 16:36:56 -07001813 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001814
1815 public void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
1816 final ContentResolver resolver = mContext.getContentResolver();
1817 Cursor c = null;
1818 int count = 0;
1819 int curScreen = 0;
1820
1821 try {
1822 c = resolver.query(uri, null, null, null, "title ASC");
1823 } catch (Exception e) {
1824 // Ignore
1825 }
1826
Dan Sandlerd5024042014-01-09 15:01:33 -05001827 // We already have a favorites database in the old provider
1828 if (c != null) {
1829 try {
1830 if (c.getCount() > 0) {
1831 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1832 final int intentIndex
1833 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1834 final int titleIndex
1835 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1836 final int iconTypeIndex
1837 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1838 final int iconIndex
1839 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1840 final int iconPackageIndex
1841 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1842 final int iconResourceIndex
1843 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1844 final int containerIndex
1845 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1846 final int itemTypeIndex
1847 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1848 final int screenIndex
1849 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1850 final int cellXIndex
1851 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1852 final int cellYIndex
1853 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1854 final int uriIndex
1855 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1856 final int displayModeIndex
1857 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001858 final int profileIndex
1859 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001860
1861 int i = 0;
1862 int curX = 0;
1863 int curY = 0;
1864
1865 final LauncherAppState app = LauncherAppState.getInstance();
1866 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1867 final int width = (int) grid.numColumns;
1868 final int height = (int) grid.numRows;
1869 final int hotseatWidth = (int) grid.numHotseatIcons;
Adam Cohen556f6132014-01-15 15:18:08 -08001870 PackageManager pm = mContext.getPackageManager();
Dan Sandlerd5024042014-01-09 15:01:33 -05001871
1872 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1873
Adam Cohen72960972014-01-15 18:13:55 -08001874 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1875 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001876 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001877
1878 while (c.moveToNext()) {
1879 final int itemType = c.getInt(itemTypeIndex);
1880 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1881 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1882 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1883 continue;
1884 }
1885
1886 final int cellX = c.getInt(cellXIndex);
1887 final int cellY = c.getInt(cellYIndex);
1888 final int screen = c.getInt(screenIndex);
1889 int container = c.getInt(containerIndex);
1890 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001891
1892 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1893 UserHandleCompat userHandle;
1894 final long userSerialNumber;
1895 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1896 userSerialNumber = c.getInt(profileIndex);
1897 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1898 } else {
1899 // Default to the serial number of this user, for older
1900 // shortcuts.
1901 userHandle = UserHandleCompat.myUserHandle();
1902 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1903 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001904 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001905 + c.getString(titleIndex) + "\" ("
1906 + cellX + "," + cellY + "@"
1907 + LauncherSettings.Favorites.containerToString(container)
1908 + "/" + screen
1909 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001910
1911 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001912
1913 final Intent intent;
1914 final ComponentName cn;
1915 try {
1916 intent = Intent.parseUri(intentStr, 0);
1917 } catch (URISyntaxException e) {
1918 // bogus intent?
1919 Launcher.addDumpLog(TAG,
1920 "skipping invalid intent uri", true);
1921 continue;
1922 }
1923
1924 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001925 if (TextUtils.isEmpty(intentStr)) {
1926 // no intent? no icon
1927 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1928 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001929 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001930 !LauncherModel.isValidPackageActivity(mContext, cn,
1931 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001932 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001933 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001934 "no longer exists.", true);
1935 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001936 } else if (container ==
1937 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1938 // Dedupe icons directly on the workspace
1939
Adam Cohen556f6132014-01-15 15:18:08 -08001940 // Canonicalize
1941 // the Play Store sets the package parameter, but Launcher
1942 // does not, so we clear that out to keep them the same
1943 intent.setPackage(null);
1944 final String key = intent.toUri(0);
1945 if (seenIntents.contains(key)) {
1946 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001947 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001948 } else {
1949 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001950 }
1951 }
1952 }
1953
1954 ContentValues values = new ContentValues(c.getColumnCount());
1955 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1956 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1957 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1958 values.put(LauncherSettings.Favorites.ICON_TYPE,
1959 c.getInt(iconTypeIndex));
1960 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1961 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1962 c.getString(iconPackageIndex));
1963 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1964 c.getString(iconResourceIndex));
1965 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1966 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1967 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1968 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1969 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001970 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001971
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001972 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1973 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001974 }
1975
1976 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1977 // In a folder or in the hotseat, preserve position
1978 values.put(LauncherSettings.Favorites.SCREEN, screen);
1979 values.put(LauncherSettings.Favorites.CELLX, cellX);
1980 values.put(LauncherSettings.Favorites.CELLY, cellY);
1981 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001982 // For items contained directly on one of the workspace screen,
1983 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001984 }
1985
1986 values.put(LauncherSettings.Favorites.CONTAINER, container);
1987
Adam Cohen72960972014-01-15 18:13:55 -08001988 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1989 shortcuts.add(values);
1990 } else {
1991 folders.add(values);
1992 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001993 }
1994
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001995 // Now that we have all the hotseat icons, let's go through them left-right
1996 // and assign valid locations for them in the new hotseat
1997 final int N = hotseat.size();
1998 for (int idx=0; idx<N; idx++) {
1999 int hotseatX = hotseat.keyAt(idx);
2000 ContentValues values = hotseat.valueAt(idx);
2001
2002 if (hotseatX == grid.hotseatAllAppsRank) {
2003 // let's drop this in the next available hole in the hotseat
2004 while (++hotseatX < hotseatWidth) {
2005 if (hotseat.get(hotseatX) == null) {
2006 // found a spot! move it here
2007 values.put(LauncherSettings.Favorites.SCREEN,
2008 hotseatX);
2009 break;
2010 }
2011 }
2012 }
2013 if (hotseatX >= hotseatWidth) {
2014 // no room for you in the hotseat? it's off to the desktop with you
2015 values.put(LauncherSettings.Favorites.CONTAINER,
2016 Favorites.CONTAINER_DESKTOP);
2017 }
2018 }
2019
Adam Cohen72960972014-01-15 18:13:55 -08002020 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
2021 // Folders first
2022 allItems.addAll(folders);
2023 // Then shortcuts
2024 allItems.addAll(shortcuts);
2025
2026 // Layout all the folders
2027 for (ContentValues values: allItems) {
2028 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
2029 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2030 // Hotseat items and folder items have already had their
2031 // location information set. Nothing to be done here.
2032 continue;
2033 }
2034 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
2035 values.put(LauncherSettings.Favorites.CELLX, curX);
2036 values.put(LauncherSettings.Favorites.CELLY, curY);
2037 curX = (curX + 1) % width;
2038 if (curX == 0) {
2039 curY = (curY + 1);
2040 }
2041 // Leave the last row of icons blank on every screen
2042 if (curY == height - 1) {
2043 curScreen = (int) generateNewScreenId();
2044 curY = 0;
2045 }
2046 }
2047
2048 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05002049 db.beginTransaction();
2050 try {
Adam Cohen72960972014-01-15 18:13:55 -08002051 for (ContentValues row: allItems) {
2052 if (row == null) continue;
2053 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05002054 < 0) {
2055 return;
2056 } else {
2057 count++;
2058 }
2059 }
2060 db.setTransactionSuccessful();
2061 } finally {
2062 db.endTransaction();
2063 }
2064 }
2065
2066 db.beginTransaction();
2067 try {
2068 for (i=0; i<=curScreen; i++) {
2069 final ContentValues values = new ContentValues();
2070 values.put(LauncherSettings.WorkspaceScreens._ID, i);
2071 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
2072 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
2073 < 0) {
2074 return;
2075 }
2076 }
2077 db.setTransactionSuccessful();
2078 } finally {
2079 db.endTransaction();
2080 }
2081 }
2082 } finally {
2083 c.close();
2084 }
2085 }
2086
2087 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
2088 + (curScreen+1) + " screens", true);
2089
2090 // ensure that new screens are created to hold these icons
2091 setFlagJustLoadedOldDb();
2092
2093 // Update max IDs; very important since we just grabbed IDs from another database
2094 mMaxItemId = initializeMaxItemId(db);
2095 mMaxScreenId = initializeMaxScreenId(db);
2096 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
2097 }
Mike Cleronb87bd162009-10-30 16:36:56 -07002098 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002099
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002100 /**
2101 * Build a query string that will match any row where the column matches
2102 * anything in the values list.
2103 */
2104 static String buildOrWhereString(String column, int[] values) {
2105 StringBuilder selectWhere = new StringBuilder();
2106 for (int i = values.length - 1; i >= 0; i--) {
2107 selectWhere.append(column).append("=").append(values[i]);
2108 if (i > 0) {
2109 selectWhere.append(" OR ");
2110 }
2111 }
2112 return selectWhere.toString();
2113 }
2114
Jeff Sharkey5aeef582014-04-14 13:26:42 -07002115 /**
2116 * Return attribute value, attempting launcher-specific namespace first
2117 * before falling back to anonymous attribute.
2118 */
2119 static String getAttributeValue(XmlResourceParser parser, String attribute) {
2120 String value = parser.getAttributeValue(
2121 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute);
2122 if (value == null) {
2123 value = parser.getAttributeValue(null, attribute);
2124 }
2125 return value;
2126 }
2127
2128 /**
2129 * Return attribute resource value, attempting launcher-specific namespace
2130 * first before falling back to anonymous attribute.
2131 */
2132 static int getAttributeResourceValue(XmlResourceParser parser, String attribute,
2133 int defaultValue) {
2134 int value = parser.getAttributeResourceValue(
2135 "http://schemas.android.com/apk/res-auto/com.android.launcher3", attribute,
2136 defaultValue);
2137 if (value == defaultValue) {
2138 value = parser.getAttributeResourceValue(null, attribute, defaultValue);
2139 }
2140 return value;
2141 }
2142
2143 private static void copyInteger(ContentValues from, ContentValues to, String key) {
2144 to.put(key, from.getAsInteger(key));
2145 }
2146
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002147 static class SqlArguments {
2148 public final String table;
2149 public final String where;
2150 public final String[] args;
2151
2152 SqlArguments(Uri url, String where, String[] args) {
2153 if (url.getPathSegments().size() == 1) {
2154 this.table = url.getPathSegments().get(0);
2155 this.where = where;
2156 this.args = args;
2157 } else if (url.getPathSegments().size() != 2) {
2158 throw new IllegalArgumentException("Invalid URI: " + url);
2159 } else if (!TextUtils.isEmpty(where)) {
2160 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
2161 } else {
2162 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07002163 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002164 this.args = null;
2165 }
2166 }
2167
2168 SqlArguments(Uri url) {
2169 if (url.getPathSegments().size() == 1) {
2170 table = url.getPathSegments().get(0);
2171 where = null;
2172 args = null;
2173 } else {
2174 throw new IllegalArgumentException("Invalid URI: " + url);
2175 }
2176 }
2177 }
Adam Cohen72960972014-01-15 18:13:55 -08002178}