blob: 1040b1173e63d5a7ac7291ed53f083913de64f4d [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
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.net.Uri;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080039import android.os.StrictMode;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050042import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070043
Sunny Goyal0fe505b2014-08-06 09:55:36 -070044import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
45import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010046import com.android.launcher3.compat.UserHandleCompat;
47import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040048import com.android.launcher3.config.ProviderConfig;
Michael Jurka8b805b12012-04-18 14:23:14 -070049
Dan Sandlerd5024042014-01-09 15:01:33 -050050import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070051import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070053import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050054import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080057 private static final String TAG = "Launcher.LauncherProvider";
58 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
Sunny Goyale87e6ab2014-11-21 22:42:53 -080060 private static final int MIN_DATABASE_VERSION = 12;
Sunny Goyal633325c2015-02-25 10:46:34 -080061 private static final int DATABASE_VERSION = 22;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062
Adam Cohene25af792013-06-06 23:08:25 -070063 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040064 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070067 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080069 static final String UPGRADED_FROM_OLD_DATABASE = "UPGRADED_FROM_OLD_DATABASE";
70 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Adam Cohena043fa82014-07-23 14:49:38 -070072 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
73
Anjali Koppal67e7cae2014-03-13 12:14:12 -070074 private LauncherProviderChangeListener mListener;
75
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070076 /**
Romain Guy73b979d2009-06-09 12:57:21 -070077 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070078 * {@link AppWidgetHost#deleteHost()} is called during database creation.
79 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
80 */
81 static final Uri CONTENT_APPWIDGET_RESET_URI =
82 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070083
Michael Jurkaa8c760d2011-04-28 14:59:33 -070084 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085
86 @Override
87 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040088 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080089 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040090 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080091 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093 return true;
94 }
95
Winson Chung0b560dd2014-01-21 13:00:26 -080096 public boolean wasNewDbCreated() {
97 return mOpenHelper.wasNewDbCreated();
98 }
99
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700100 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
101 mListener = listener;
102 }
103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 @Override
105 public String getType(Uri uri) {
106 SqlArguments args = new SqlArguments(uri, null, null);
107 if (TextUtils.isEmpty(args.where)) {
108 return "vnd.android.cursor.dir/" + args.table;
109 } else {
110 return "vnd.android.cursor.item/" + args.table;
111 }
112 }
113
114 @Override
115 public Cursor query(Uri uri, String[] projection, String selection,
116 String[] selectionArgs, String sortOrder) {
117
118 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
119 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
120 qb.setTables(args.table);
121
Romain Guy73b979d2009-06-09 12:57:21 -0700122 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
124 result.setNotificationUri(getContext().getContentResolver(), uri);
125
126 return result;
127 }
128
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 private static long dbInsertAndCheck(DatabaseHelper helper,
130 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500131 if (values == null) {
132 throw new RuntimeException("Error: attempting to insert null values");
133 }
Adam Cohen71483f42014-05-15 14:04:01 -0700134 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 throw new RuntimeException("Error: attempting to add item without specifying an id");
136 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500137 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 return db.insert(table, nullColumnHack, values);
139 }
140
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141 @Override
142 public Uri insert(Uri uri, ContentValues initialValues) {
143 SqlArguments args = new SqlArguments(uri);
144
Adam Cohena043fa82014-07-23 14:49:38 -0700145 // In very limited cases, we support system|signature permission apps to add to the db
146 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
147 if (externalAdd != null && "true".equals(externalAdd)) {
148 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
149 return null;
150 }
151 }
152
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400154 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800156 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800157
158 uri = ContentUris.withAppendedId(uri, rowId);
159 sendNotify(uri);
160
161 return uri;
162 }
163
Adam Cohena043fa82014-07-23 14:49:38 -0700164
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165 @Override
166 public int bulkInsert(Uri uri, ContentValues[] values) {
167 SqlArguments args = new SqlArguments(uri);
168
169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
170 db.beginTransaction();
171 try {
172 int numValues = values.length;
173 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400174 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
176 return 0;
177 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178 }
179 db.setTransactionSuccessful();
180 } finally {
181 db.endTransaction();
182 }
183
184 sendNotify(uri);
185 return values.length;
186 }
187
188 @Override
Yura085c8532014-02-11 15:15:29 +0000189 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
190 throws OperationApplicationException {
191 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
192 db.beginTransaction();
193 try {
194 ContentProviderResult[] result = super.applyBatch(operations);
195 db.setTransactionSuccessful();
196 return result;
197 } finally {
198 db.endTransaction();
199 }
200 }
201
202 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 public int delete(Uri uri, String selection, String[] selectionArgs) {
204 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
205
206 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
207 int count = db.delete(args.table, args.where, args.args);
208 if (count > 0) sendNotify(uri);
209
210 return count;
211 }
212
213 @Override
214 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
215 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
216
Chris Wren1ada10d2013-09-13 18:01:38 -0400217 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
219 int count = db.update(args.table, values, args.where, args.args);
220 if (count > 0) sendNotify(uri);
221
222 return count;
223 }
224
225 private void sendNotify(Uri uri) {
226 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400230
231 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400232 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700233 if (mListener != null) {
234 mListener.onLauncherProviderChange();
235 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400236 }
237
Sunny Goyal633325c2015-02-25 10:46:34 -0800238 private static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400239 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240 }
241
Adam Cohendcd297f2013-06-18 13:13:40 -0700242 public long generateNewItemId() {
243 return mOpenHelper.generateNewItemId();
244 }
245
Winson Chungc763c4e2013-07-19 13:49:06 -0700246 public void updateMaxItemId(long id) {
247 mOpenHelper.updateMaxItemId(id);
248 }
249
Adam Cohendcd297f2013-06-18 13:13:40 -0700250 public long generateNewScreenId() {
251 return mOpenHelper.generateNewScreenId();
252 }
253
254 // This is only required one time while loading the workspace during the
255 // upgrade path, and should never be called from anywhere else.
256 public void updateMaxScreenId(long maxScreenId) {
257 mOpenHelper.updateMaxScreenId(maxScreenId);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700258 }
259
Brian Muramatsu5524b492012-10-02 16:55:54 -0700260 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700261 * Clears all the data for a fresh start.
262 */
263 synchronized public void createEmptyDB() {
264 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
265 }
266
Sunny Goyal33d44382014-10-16 09:24:19 -0700267 public void clearFlagEmptyDbCreated() {
268 String spKey = LauncherAppState.getSharedPreferencesKey();
269 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
270 .edit()
271 .remove(EMPTY_DATABASE_CREATED)
272 .commit();
273 }
274
Sunny Goyal42de82f2014-09-26 22:09:29 -0700275 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700276 * Loads the default workspace based on the following priority scheme:
277 * 1) From a package provided by play store
278 * 2) From a partner configuration APK, already in the system image
279 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700280 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700281 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400282 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700283 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700284
Winson Chungc763c4e2013-07-19 13:49:06 -0700285 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500286 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200287
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700288 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700289 mOpenHelper.mAppWidgetHost, mOpenHelper);
290
291 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700292 final Partner partner = Partner.get(getContext().getPackageManager());
293 if (partner != null && partner.hasDefaultLayout()) {
294 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700295 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700296 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700297 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700298 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
299 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700300 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700301 }
302 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700303
Sunny Goyal9d219682014-10-23 14:21:02 -0700304 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700305 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700306 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700307 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800308
309 // There might be some partially restored DB items, due to buggy restore logic in
310 // previous versions of launcher.
311 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700312 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700313 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
314 && usingExternallyProvidedLayout) {
315 // Unable to load external layout. Cleanup and load the internal layout.
316 createEmptyDB();
317 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
318 getDefaultLayoutParser());
319 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700320 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700321 }
322 }
323
Sunny Goyal9d219682014-10-23 14:21:02 -0700324 private DefaultLayoutParser getDefaultLayoutParser() {
325 int defaultLayout = LauncherAppState.getInstance()
326 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
327 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
328 mOpenHelper, getContext().getResources(), defaultLayout);
329 }
330
Dan Sandlerd5024042014-01-09 15:01:33 -0500331 public void migrateLauncher2Shortcuts() {
332 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400333 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500334 }
335
Sunny Goyal08f72612015-01-05 13:41:43 -0800336 public void updateFolderItemsRank() {
337 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
338 }
339
Dan Sandlerd5024042014-01-09 15:01:33 -0500340 public void deleteDatabase() {
341 // Are you sure? (y/n)
342 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500343 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500344 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500345 if (dbFile.exists()) {
346 SQLiteDatabase.deleteDatabase(dbFile);
347 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500348 mOpenHelper = new DatabaseHelper(getContext());
349 }
350
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700351 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700353 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700354 private long mMaxItemId = -1;
355 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356
Winson Chung0b560dd2014-01-21 13:00:26 -0800357 private boolean mNewDbCreated = false;
358
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100360 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800361 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700362 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700363
364 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
365 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700366 if (mMaxItemId == -1) {
367 mMaxItemId = initializeMaxItemId(getWritableDatabase());
368 }
369 if (mMaxScreenId == -1) {
370 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700371 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800372 }
373
Winson Chung0b560dd2014-01-21 13:00:26 -0800374 public boolean wasNewDbCreated() {
375 return mNewDbCreated;
376 }
377
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700378 /**
379 * Send notification that we've deleted the {@link AppWidgetHost},
380 * probably as part of the initial database creation. The receiver may
381 * want to re-call {@link AppWidgetHost#startListening()} to ensure
382 * callbacks are correctly set.
383 */
384 private void sendAppWidgetResetNotify() {
385 final ContentResolver resolver = mContext.getContentResolver();
386 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
387 }
388
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800389 @Override
390 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800391 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700392
Adam Cohendcd297f2013-06-18 13:13:40 -0700393 mMaxItemId = 1;
394 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800395 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700396
Kenny Guyed131872014-04-30 03:02:21 +0100397 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
398 long userSerialNumber = userManager.getSerialNumberForUser(
399 UserHandleCompat.myUserHandle());
400
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800401 db.execSQL("CREATE TABLE favorites (" +
402 "_id INTEGER PRIMARY KEY," +
403 "title TEXT," +
404 "intent TEXT," +
405 "container INTEGER," +
406 "screen INTEGER," +
407 "cellX INTEGER," +
408 "cellY INTEGER," +
409 "spanX INTEGER," +
410 "spanY INTEGER," +
411 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700412 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800413 "isShortcut INTEGER," +
414 "iconType INTEGER," +
415 "iconPackage TEXT," +
416 "iconResource TEXT," +
417 "icon BLOB," +
418 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400419 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400420 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500421 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100422 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800423 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
424 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700426 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800427
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700428 // Database was just created, so wipe any previous widgets
429 if (mAppWidgetHost != null) {
430 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700431 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800432 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700433
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800434 // Fresh and clean launcher DB.
435 mMaxItemId = initializeMaxItemId(db);
436 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800437 }
438
Adam Cohendcd297f2013-06-18 13:13:40 -0700439 private void addWorkspacesTable(SQLiteDatabase db) {
440 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyal633325c2015-02-25 10:46:34 -0800441 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400442 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
443 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700444 ");");
445 }
446
Adam Cohen119285e2014-04-02 16:59:08 -0700447 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700448 // Delete items directly on the workspace who's screen id doesn't exist
449 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
450 // AND container = -100"
451 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
452 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700453 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700454 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
455 " AND " +
456 LauncherSettings.Favorites.CONTAINER + " = " +
457 LauncherSettings.Favorites.CONTAINER_DESKTOP;
458 db.execSQL(removeOrphanedDesktopItems);
459
460 // Delete items contained in folders which no longer exist (after above statement)
461 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
462 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
463 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
464 " WHERE " +
465 LauncherSettings.Favorites.CONTAINER + " <> " +
466 LauncherSettings.Favorites.CONTAINER_DESKTOP +
467 " AND "
468 + LauncherSettings.Favorites.CONTAINER + " <> " +
469 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
470 " AND "
471 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
472 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
473 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
474 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
475 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700476 }
477
Winson Chungc763c4e2013-07-19 13:49:06 -0700478 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400479 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700480 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
481 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700482 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
483 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700484 editor.commit();
485 }
486
Winson Chungc763c4e2013-07-19 13:49:06 -0700487 private void setFlagEmptyDbCreated() {
488 String spKey = LauncherAppState.getSharedPreferencesKey();
489 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
490 SharedPreferences.Editor editor = sp.edit();
491 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
492 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
493 editor.commit();
494 }
495
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 @Override
497 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700498 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700499
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800500 int version = oldVersion;
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800501 if (version < MIN_DATABASE_VERSION) {
502 // The version cannot be lower that this, as Launcher3 never supported a lower
503 // version of the DB.
504 createEmptyDB(db);
505 version = DATABASE_VERSION;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700506 }
507
Adam Cohendcd297f2013-06-18 13:13:40 -0700508 if (version < 13) {
509 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
510 // to persist workspace screens and their relative order.
511 mMaxScreenId = 0;
512
Adam Cohendcd297f2013-06-18 13:13:40 -0700513 addWorkspacesTable(db);
514 version = 13;
515 }
516
Chris Wrend5e66bf2013-09-16 14:02:29 -0400517 if (version < 14) {
518 db.beginTransaction();
519 try {
520 // Insert new column for holding widget provider name
521 db.execSQL("ALTER TABLE favorites " +
522 "ADD COLUMN appWidgetProvider TEXT;");
523 db.setTransactionSuccessful();
524 version = 14;
525 } catch (SQLException ex) {
526 // Old version remains, which means we wipe old data
527 Log.e(TAG, ex.getMessage(), ex);
528 } finally {
529 db.endTransaction();
530 }
531 }
532
Chris Wren1ada10d2013-09-13 18:01:38 -0400533 if (version < 15) {
534 db.beginTransaction();
535 try {
536 // Insert new column for holding update timestamp
537 db.execSQL("ALTER TABLE favorites " +
538 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
539 db.execSQL("ALTER TABLE workspaceScreens " +
540 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
541 db.setTransactionSuccessful();
542 version = 15;
543 } catch (SQLException ex) {
544 // Old version remains, which means we wipe old data
545 Log.e(TAG, ex.getMessage(), ex);
546 } finally {
547 db.endTransaction();
548 }
549 }
550
Chris Wrenf4d08112014-01-16 18:13:56 -0500551
552 if (version < 16) {
553 db.beginTransaction();
554 try {
555 // Insert new column for holding restore status
556 db.execSQL("ALTER TABLE favorites " +
557 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
558 db.setTransactionSuccessful();
559 version = 16;
560 } catch (SQLException ex) {
561 // Old version remains, which means we wipe old data
562 Log.e(TAG, ex.getMessage(), ex);
563 } finally {
564 db.endTransaction();
565 }
566 }
567
Adam Cohen71e03b92014-02-21 14:09:53 -0800568 if (version < 17) {
569 // We use the db version upgrade here to identify users who may not have seen
570 // clings yet (because they weren't available), but for whom the clings are now
571 // available (tablet users). Because one of the possible cling flows (migration)
572 // is very destructive (wipes out workspaces), we want to prevent this from showing
573 // until clear data. We do so by marking that the clings have been shown.
574 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
575 version = 17;
576 }
577
Adam Cohen119285e2014-04-02 16:59:08 -0700578 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700579 // No-op
580 version = 18;
581 }
582
583 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700584 // Due to a data loss bug, some users may have items associated with screen ids
585 // which no longer exist. Since this can cause other problems, and since the user
586 // will never see these items anyway, we use database upgrade as an opportunity to
587 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700588 removeOrphanedItems(db);
589 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700590 }
591
Kenny Guyed131872014-04-30 03:02:21 +0100592 if (version < 20) {
593 // Add userId column
594 if (addProfileColumn(db)) {
595 version = 20;
596 }
597 // else old version remains, which means we wipe old data
598 }
599
Sunny Goyal08f72612015-01-05 13:41:43 -0800600 if (version < 21) {
601 if (updateFolderItemsRank(db, true)) {
602 version = 21;
603 }
604 }
605
Sunny Goyal633325c2015-02-25 10:46:34 -0800606 if (version == 21) {
607 // Recreate workspace table with screen id a primary key
608 if (recreateWorkspaceTable(db)) {
609 version = 22;
610 }
611 }
612
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800614 Log.w(TAG, "Destroying all old data.");
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800615 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
617 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800618
Adam Cohen9b1d0622014-05-21 19:01:57 -0700619 @Override
620 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
621 // This shouldn't happen -- throw our hands up in the air and start over.
622 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
623 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700624 createEmptyDB(db);
625 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700626
Sunny Goyal42de82f2014-09-26 22:09:29 -0700627
628 /**
629 * Clears all the data for a fresh start.
630 */
631 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700632 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
633 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
634 onCreate(db);
635 }
636
Sunny Goyal633325c2015-02-25 10:46:34 -0800637 /**
638 * Recreates workspace table and migrates data to the new table.
639 */
640 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
641 db.beginTransaction();
642 try {
643 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
644 new String[] {LauncherSettings.WorkspaceScreens._ID},
645 null, null, null, null,
646 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
647 ArrayList<Long> sortedIDs = new ArrayList<Long>();
648 long maxId = 0;
649 try {
650 while (c.moveToNext()) {
651 Long id = c.getLong(0);
652 if (!sortedIDs.contains(id)) {
653 sortedIDs.add(id);
654 maxId = Math.max(maxId, id);
655 }
656 }
657 } finally {
658 c.close();
659 }
660
661 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
662 addWorkspacesTable(db);
663
664 // Add all screen ids back
665 int total = sortedIDs.size();
666 for (int i = 0; i < total; i++) {
667 ContentValues values = new ContentValues();
668 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
669 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
670 addModifiedTime(values);
671 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
672 }
673 db.setTransactionSuccessful();
674 mMaxScreenId = maxId;
675 } catch (SQLException ex) {
676 // Old version remains, which means we wipe old data
677 Log.e(TAG, ex.getMessage(), ex);
678 return false;
679 } finally {
680 db.endTransaction();
681 }
682 return true;
683 }
684
Sunny Goyal08f72612015-01-05 13:41:43 -0800685 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
686 db.beginTransaction();
687 try {
688 if (addRankColumn) {
689 // Insert new column for holding rank
690 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
691 }
692
693 // Get a map for folder ID to folder width
694 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
695 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
696 + " GROUP BY container;",
697 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
698
699 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800700 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
701 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800702 new Object[] {c.getLong(1) + 1, c.getLong(0)});
703 }
704
705 c.close();
706 db.setTransactionSuccessful();
707 } catch (SQLException ex) {
708 // Old version remains, which means we wipe old data
709 Log.e(TAG, ex.getMessage(), ex);
710 return false;
711 } finally {
712 db.endTransaction();
713 }
714 return true;
715 }
716
Kenny Guyed131872014-04-30 03:02:21 +0100717 private boolean addProfileColumn(SQLiteDatabase db) {
718 db.beginTransaction();
719 try {
720 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
721 // Default to the serial number of this user, for older
722 // shortcuts.
723 long userSerialNumber = userManager.getSerialNumberForUser(
724 UserHandleCompat.myUserHandle());
725 // Insert new column for holding user serial number
726 db.execSQL("ALTER TABLE favorites " +
727 "ADD COLUMN profileId INTEGER DEFAULT "
728 + userSerialNumber + ";");
729 db.setTransactionSuccessful();
730 } catch (SQLException ex) {
731 // Old version remains, which means we wipe old data
732 Log.e(TAG, ex.getMessage(), ex);
733 return false;
734 } finally {
735 db.endTransaction();
736 }
737 return true;
738 }
739
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700740 // Generates a new ID to use for an object in your database. This method should be only
741 // called from the main UI thread. As an exception, we do call it when we call the
742 // constructor from the worker thread; however, this doesn't extend until after the
743 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
744 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700745 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700746 public long generateNewItemId() {
747 if (mMaxItemId < 0) {
748 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700749 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700750 mMaxItemId += 1;
751 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700752 }
753
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700754 @Override
755 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
756 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
757 }
758
Winson Chungc763c4e2013-07-19 13:49:06 -0700759 public void updateMaxItemId(long id) {
760 mMaxItemId = id + 1;
761 }
762
Chris Wren5dee7af2013-12-20 17:22:11 -0500763 public void checkId(String table, ContentValues values) {
764 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
765 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
766 mMaxScreenId = Math.max(id, mMaxScreenId);
767 } else {
768 mMaxItemId = Math.max(id, mMaxItemId);
769 }
770 }
771
Adam Cohendcd297f2013-06-18 13:13:40 -0700772 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700773 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
774
775 // get the result
776 final int maxIdIndex = 0;
777 long id = -1;
778 if (c != null && c.moveToNext()) {
779 id = c.getLong(maxIdIndex);
780 }
Michael Jurka5130e402011-10-13 04:55:35 -0700781 if (c != null) {
782 c.close();
783 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700784
785 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700786 throw new RuntimeException("Error: could not query max item id");
787 }
788
789 return id;
790 }
791
792 // Generates a new ID to use for an workspace screen in your database. This method
793 // should be only called from the main UI thread. As an exception, we do call it when we
794 // call the constructor from the worker thread; however, this doesn't extend until after the
795 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
796 // after that point
797 public long generateNewScreenId() {
798 if (mMaxScreenId < 0) {
799 throw new RuntimeException("Error: max screen id was not initialized");
800 }
801 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800802 // Log to disk
803 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 return mMaxScreenId;
805 }
806
807 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800808 // Log to disk
809 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700810 mMaxScreenId = maxScreenId;
811 }
812
813 private long initializeMaxScreenId(SQLiteDatabase db) {
814 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
815
816 // get the result
817 final int maxIdIndex = 0;
818 long id = -1;
819 if (c != null && c.moveToNext()) {
820 id = c.getLong(maxIdIndex);
821 }
822 if (c != null) {
823 c.close();
824 }
825
826 if (id == -1) {
827 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700828 }
829
Winson Chunga90303b2013-11-15 13:05:06 -0800830 // Log to disk
831 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700832 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800833 }
834
Adam Cohena043fa82014-07-23 14:49:38 -0700835 private boolean initializeExternalAdd(ContentValues values) {
836 // 1. Ensure that externally added items have a valid item id
837 long id = generateNewItemId();
838 values.put(LauncherSettings.Favorites._ID, id);
839
840 // 2. In the case of an app widget, and if no app widget id is specified, we
841 // attempt allocate and bind the widget.
842 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
843 if (itemType != null &&
844 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
845 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
846
847 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
848 ComponentName cn = ComponentName.unflattenFromString(
849 values.getAsString(Favorites.APPWIDGET_PROVIDER));
850
851 if (cn != null) {
852 try {
853 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700854 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700855 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700856 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700857 }
858 } catch (RuntimeException e) {
859 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700860 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700861 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700862 } else {
863 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700864 }
865 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700866
867 // Add screen id if not present
868 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
869 if (!addScreenIdIfNecessary(screenId)) {
870 return false;
871 }
Adam Cohena043fa82014-07-23 14:49:38 -0700872 return true;
873 }
874
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700875 // Returns true of screen id exists, or if successfully added
876 private boolean addScreenIdIfNecessary(long screenId) {
877 if (!hasScreenId(screenId)) {
878 int rank = getMaxScreenRank() + 1;
879
880 ContentValues v = new ContentValues();
881 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
882 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
883 if (dbInsertAndCheck(this, getWritableDatabase(),
884 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
885 return false;
886 }
887 }
888 return true;
889 }
890
891 private boolean hasScreenId(long screenId) {
892 SQLiteDatabase db = getWritableDatabase();
893 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
894 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
895 if (c != null) {
896 int count = c.getCount();
897 c.close();
898 return count > 0;
899 } else {
900 return false;
901 }
902 }
903
904 private int getMaxScreenRank() {
905 SQLiteDatabase db = getWritableDatabase();
906 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
907 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
908
909 // get the result
910 final int maxRankIndex = 0;
911 int rank = -1;
912 if (c != null && c.moveToNext()) {
913 rank = c.getInt(maxRankIndex);
914 }
915 if (c != null) {
916 c.close();
917 }
918
919 return rank;
920 }
921
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700922 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700923 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700924 // TODO: Use multiple loaders with fall-back and transaction.
925 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700926
927 // Add the screens specified by the items above
928 Collections.sort(screenIds);
929 int rank = 0;
930 ContentValues values = new ContentValues();
931 for (Long id : screenIds) {
932 values.clear();
933 values.put(LauncherSettings.WorkspaceScreens._ID, id);
934 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
935 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
936 throw new RuntimeException("Failed initialize screen table"
937 + "from default layout");
938 }
939 rank++;
940 }
941
942 // Ensure that the max ids are initialized
943 mMaxItemId = initializeMaxItemId(db);
944 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700945
Adam Cohen71483f42014-05-15 14:04:01 -0700946 return count;
947 }
948
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700949 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500950 final ContentResolver resolver = mContext.getContentResolver();
951 Cursor c = null;
952 int count = 0;
953 int curScreen = 0;
954
955 try {
956 c = resolver.query(uri, null, null, null, "title ASC");
957 } catch (Exception e) {
958 // Ignore
959 }
960
Dan Sandlerd5024042014-01-09 15:01:33 -0500961 // We already have a favorites database in the old provider
962 if (c != null) {
963 try {
964 if (c.getCount() > 0) {
965 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
966 final int intentIndex
967 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
968 final int titleIndex
969 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
970 final int iconTypeIndex
971 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
972 final int iconIndex
973 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
974 final int iconPackageIndex
975 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
976 final int iconResourceIndex
977 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
978 final int containerIndex
979 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
980 final int itemTypeIndex
981 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
982 final int screenIndex
983 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
984 final int cellXIndex
985 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
986 final int cellYIndex
987 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
988 final int uriIndex
989 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
990 final int displayModeIndex
991 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100992 final int profileIndex
993 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500994
995 int i = 0;
996 int curX = 0;
997 int curY = 0;
998
999 final LauncherAppState app = LauncherAppState.getInstance();
1000 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1001 final int width = (int) grid.numColumns;
1002 final int height = (int) grid.numRows;
1003 final int hotseatWidth = (int) grid.numHotseatIcons;
1004
1005 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1006
Adam Cohen72960972014-01-15 18:13:55 -08001007 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1008 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001009 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001010
1011 while (c.moveToNext()) {
1012 final int itemType = c.getInt(itemTypeIndex);
1013 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1014 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1015 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1016 continue;
1017 }
1018
1019 final int cellX = c.getInt(cellXIndex);
1020 final int cellY = c.getInt(cellYIndex);
1021 final int screen = c.getInt(screenIndex);
1022 int container = c.getInt(containerIndex);
1023 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001024
1025 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1026 UserHandleCompat userHandle;
1027 final long userSerialNumber;
1028 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1029 userSerialNumber = c.getInt(profileIndex);
1030 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1031 } else {
1032 // Default to the serial number of this user, for older
1033 // shortcuts.
1034 userHandle = UserHandleCompat.myUserHandle();
1035 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1036 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001037
1038 if (userHandle == null) {
1039 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1040 continue;
1041 }
1042
Dan Sandlerd5024042014-01-09 15:01:33 -05001043 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001044 + c.getString(titleIndex) + "\" ("
1045 + cellX + "," + cellY + "@"
1046 + LauncherSettings.Favorites.containerToString(container)
1047 + "/" + screen
1048 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001049
1050 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001051
1052 final Intent intent;
1053 final ComponentName cn;
1054 try {
1055 intent = Intent.parseUri(intentStr, 0);
1056 } catch (URISyntaxException e) {
1057 // bogus intent?
1058 Launcher.addDumpLog(TAG,
1059 "skipping invalid intent uri", true);
1060 continue;
1061 }
1062
1063 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001064 if (TextUtils.isEmpty(intentStr)) {
1065 // no intent? no icon
1066 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1067 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001068 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001069 !LauncherModel.isValidPackageActivity(mContext, cn,
1070 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001071 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001072 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001073 "no longer exists.", true);
1074 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001075 } else if (container ==
1076 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1077 // Dedupe icons directly on the workspace
1078
Adam Cohen556f6132014-01-15 15:18:08 -08001079 // Canonicalize
1080 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001081 // does not, so we clear that out to keep them the same.
1082 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001083 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001084 int flags = intent.getFlags();
1085 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001086 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001087 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001088 if (seenIntents.contains(key)) {
1089 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001090 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001091 } else {
1092 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001093 }
1094 }
1095 }
1096
1097 ContentValues values = new ContentValues(c.getColumnCount());
1098 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1099 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1100 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1101 values.put(LauncherSettings.Favorites.ICON_TYPE,
1102 c.getInt(iconTypeIndex));
1103 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1104 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1105 c.getString(iconPackageIndex));
1106 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1107 c.getString(iconResourceIndex));
1108 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1109 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1110 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1111 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1112 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001113 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001114
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001115 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1116 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001117 }
1118
1119 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1120 // In a folder or in the hotseat, preserve position
1121 values.put(LauncherSettings.Favorites.SCREEN, screen);
1122 values.put(LauncherSettings.Favorites.CELLX, cellX);
1123 values.put(LauncherSettings.Favorites.CELLY, cellY);
1124 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001125 // For items contained directly on one of the workspace screen,
1126 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001127 }
1128
1129 values.put(LauncherSettings.Favorites.CONTAINER, container);
1130
Adam Cohen72960972014-01-15 18:13:55 -08001131 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1132 shortcuts.add(values);
1133 } else {
1134 folders.add(values);
1135 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001136 }
1137
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001138 // Now that we have all the hotseat icons, let's go through them left-right
1139 // and assign valid locations for them in the new hotseat
1140 final int N = hotseat.size();
1141 for (int idx=0; idx<N; idx++) {
1142 int hotseatX = hotseat.keyAt(idx);
1143 ContentValues values = hotseat.valueAt(idx);
1144
1145 if (hotseatX == grid.hotseatAllAppsRank) {
1146 // let's drop this in the next available hole in the hotseat
1147 while (++hotseatX < hotseatWidth) {
1148 if (hotseat.get(hotseatX) == null) {
1149 // found a spot! move it here
1150 values.put(LauncherSettings.Favorites.SCREEN,
1151 hotseatX);
1152 break;
1153 }
1154 }
1155 }
1156 if (hotseatX >= hotseatWidth) {
1157 // no room for you in the hotseat? it's off to the desktop with you
1158 values.put(LauncherSettings.Favorites.CONTAINER,
1159 Favorites.CONTAINER_DESKTOP);
1160 }
1161 }
1162
Adam Cohen72960972014-01-15 18:13:55 -08001163 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1164 // Folders first
1165 allItems.addAll(folders);
1166 // Then shortcuts
1167 allItems.addAll(shortcuts);
1168
1169 // Layout all the folders
1170 for (ContentValues values: allItems) {
1171 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1172 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1173 // Hotseat items and folder items have already had their
1174 // location information set. Nothing to be done here.
1175 continue;
1176 }
1177 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1178 values.put(LauncherSettings.Favorites.CELLX, curX);
1179 values.put(LauncherSettings.Favorites.CELLY, curY);
1180 curX = (curX + 1) % width;
1181 if (curX == 0) {
1182 curY = (curY + 1);
1183 }
1184 // Leave the last row of icons blank on every screen
1185 if (curY == height - 1) {
1186 curScreen = (int) generateNewScreenId();
1187 curY = 0;
1188 }
1189 }
1190
1191 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001192 db.beginTransaction();
1193 try {
Adam Cohen72960972014-01-15 18:13:55 -08001194 for (ContentValues row: allItems) {
1195 if (row == null) continue;
1196 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001197 < 0) {
1198 return;
1199 } else {
1200 count++;
1201 }
1202 }
1203 db.setTransactionSuccessful();
1204 } finally {
1205 db.endTransaction();
1206 }
1207 }
1208
1209 db.beginTransaction();
1210 try {
1211 for (i=0; i<=curScreen; i++) {
1212 final ContentValues values = new ContentValues();
1213 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1214 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1215 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1216 < 0) {
1217 return;
1218 }
1219 }
1220 db.setTransactionSuccessful();
1221 } finally {
1222 db.endTransaction();
1223 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001224
1225 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001226 }
1227 } finally {
1228 c.close();
1229 }
1230 }
1231
1232 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1233 + (curScreen+1) + " screens", true);
1234
1235 // ensure that new screens are created to hold these icons
1236 setFlagJustLoadedOldDb();
1237
1238 // Update max IDs; very important since we just grabbed IDs from another database
1239 mMaxItemId = initializeMaxItemId(db);
1240 mMaxScreenId = initializeMaxScreenId(db);
1241 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1242 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001243 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001244
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001245 static class SqlArguments {
1246 public final String table;
1247 public final String where;
1248 public final String[] args;
1249
1250 SqlArguments(Uri url, String where, String[] args) {
1251 if (url.getPathSegments().size() == 1) {
1252 this.table = url.getPathSegments().get(0);
1253 this.where = where;
1254 this.args = args;
1255 } else if (url.getPathSegments().size() != 2) {
1256 throw new IllegalArgumentException("Invalid URI: " + url);
1257 } else if (!TextUtils.isEmpty(where)) {
1258 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1259 } else {
1260 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001261 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001262 this.args = null;
1263 }
1264 }
1265
1266 SqlArguments(Uri url) {
1267 if (url.getPathSegments().size() == 1) {
1268 table = url.getPathSegments().get(0);
1269 where = null;
1270 args = null;
1271 } else {
1272 throw new IllegalArgumentException("Invalid URI: " + url);
1273 }
1274 }
1275 }
Adam Cohen72960972014-01-15 18:13:55 -08001276}