blob: 3888b709cc022c7d195ebcf74a702b49a9c7639b [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 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700308 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700309 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
310 && usingExternallyProvidedLayout) {
311 // Unable to load external layout. Cleanup and load the internal layout.
312 createEmptyDB();
313 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
314 getDefaultLayoutParser());
315 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700316 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700317 }
318 }
319
Sunny Goyal9d219682014-10-23 14:21:02 -0700320 private DefaultLayoutParser getDefaultLayoutParser() {
321 int defaultLayout = LauncherAppState.getInstance()
322 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
323 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
324 mOpenHelper, getContext().getResources(), defaultLayout);
325 }
326
Dan Sandlerd5024042014-01-09 15:01:33 -0500327 public void migrateLauncher2Shortcuts() {
328 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400329 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500330 }
331
Sunny Goyal08f72612015-01-05 13:41:43 -0800332 public void updateFolderItemsRank() {
333 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
334 }
335
Dan Sandlerd5024042014-01-09 15:01:33 -0500336 public void deleteDatabase() {
337 // Are you sure? (y/n)
338 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500339 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500340 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500341 if (dbFile.exists()) {
342 SQLiteDatabase.deleteDatabase(dbFile);
343 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500344 mOpenHelper = new DatabaseHelper(getContext());
345 }
346
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700347 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 private final Context mContext;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700349 private final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700350 private long mMaxItemId = -1;
351 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352
Winson Chung0b560dd2014-01-21 13:00:26 -0800353 private boolean mNewDbCreated = false;
354
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100356 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700358 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700359
360 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
361 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700362 if (mMaxItemId == -1) {
363 mMaxItemId = initializeMaxItemId(getWritableDatabase());
364 }
365 if (mMaxScreenId == -1) {
366 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700367 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800368 }
369
Winson Chung0b560dd2014-01-21 13:00:26 -0800370 public boolean wasNewDbCreated() {
371 return mNewDbCreated;
372 }
373
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700374 /**
375 * Send notification that we've deleted the {@link AppWidgetHost},
376 * probably as part of the initial database creation. The receiver may
377 * want to re-call {@link AppWidgetHost#startListening()} to ensure
378 * callbacks are correctly set.
379 */
380 private void sendAppWidgetResetNotify() {
381 final ContentResolver resolver = mContext.getContentResolver();
382 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
383 }
384
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800385 @Override
386 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800387 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700388
Adam Cohendcd297f2013-06-18 13:13:40 -0700389 mMaxItemId = 1;
390 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800391 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700392
Kenny Guyed131872014-04-30 03:02:21 +0100393 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
394 long userSerialNumber = userManager.getSerialNumberForUser(
395 UserHandleCompat.myUserHandle());
396
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 db.execSQL("CREATE TABLE favorites (" +
398 "_id INTEGER PRIMARY KEY," +
399 "title TEXT," +
400 "intent TEXT," +
401 "container INTEGER," +
402 "screen INTEGER," +
403 "cellX INTEGER," +
404 "cellY INTEGER," +
405 "spanX INTEGER," +
406 "spanY INTEGER," +
407 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700408 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800409 "isShortcut INTEGER," +
410 "iconType INTEGER," +
411 "iconPackage TEXT," +
412 "iconResource TEXT," +
413 "icon BLOB," +
414 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400415 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400416 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500417 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100418 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800419 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
420 "rank INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800421 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700422 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800423
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700424 // Database was just created, so wipe any previous widgets
425 if (mAppWidgetHost != null) {
426 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700427 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800428 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700429
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800430 // Fresh and clean launcher DB.
431 mMaxItemId = initializeMaxItemId(db);
432 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800433 }
434
Adam Cohendcd297f2013-06-18 13:13:40 -0700435 private void addWorkspacesTable(SQLiteDatabase db) {
436 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyal633325c2015-02-25 10:46:34 -0800437 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400438 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
439 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700440 ");");
441 }
442
Adam Cohen119285e2014-04-02 16:59:08 -0700443 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700444 // Delete items directly on the workspace who's screen id doesn't exist
445 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
446 // AND container = -100"
447 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
448 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700449 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700450 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
451 " AND " +
452 LauncherSettings.Favorites.CONTAINER + " = " +
453 LauncherSettings.Favorites.CONTAINER_DESKTOP;
454 db.execSQL(removeOrphanedDesktopItems);
455
456 // Delete items contained in folders which no longer exist (after above statement)
457 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
458 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
459 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
460 " WHERE " +
461 LauncherSettings.Favorites.CONTAINER + " <> " +
462 LauncherSettings.Favorites.CONTAINER_DESKTOP +
463 " AND "
464 + LauncherSettings.Favorites.CONTAINER + " <> " +
465 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
466 " AND "
467 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
468 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
469 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
470 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
471 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700472 }
473
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400475 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700476 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
477 SharedPreferences.Editor editor = sp.edit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700478 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, true);
479 editor.putBoolean(EMPTY_DATABASE_CREATED, false);
Michael Jurkab85f8a42012-04-25 15:48:32 -0700480 editor.commit();
481 }
482
Winson Chungc763c4e2013-07-19 13:49:06 -0700483 private void setFlagEmptyDbCreated() {
484 String spKey = LauncherAppState.getSharedPreferencesKey();
485 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
486 SharedPreferences.Editor editor = sp.edit();
487 editor.putBoolean(EMPTY_DATABASE_CREATED, true);
488 editor.putBoolean(UPGRADED_FROM_OLD_DATABASE, false);
489 editor.commit();
490 }
491
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492 @Override
493 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700494 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700495
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 int version = oldVersion;
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800497 if (version < MIN_DATABASE_VERSION) {
498 // The version cannot be lower that this, as Launcher3 never supported a lower
499 // version of the DB.
500 createEmptyDB(db);
501 version = DATABASE_VERSION;
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700502 }
503
Adam Cohendcd297f2013-06-18 13:13:40 -0700504 if (version < 13) {
505 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
506 // to persist workspace screens and their relative order.
507 mMaxScreenId = 0;
508
Adam Cohendcd297f2013-06-18 13:13:40 -0700509 addWorkspacesTable(db);
510 version = 13;
511 }
512
Chris Wrend5e66bf2013-09-16 14:02:29 -0400513 if (version < 14) {
514 db.beginTransaction();
515 try {
516 // Insert new column for holding widget provider name
517 db.execSQL("ALTER TABLE favorites " +
518 "ADD COLUMN appWidgetProvider TEXT;");
519 db.setTransactionSuccessful();
520 version = 14;
521 } catch (SQLException ex) {
522 // Old version remains, which means we wipe old data
523 Log.e(TAG, ex.getMessage(), ex);
524 } finally {
525 db.endTransaction();
526 }
527 }
528
Chris Wren1ada10d2013-09-13 18:01:38 -0400529 if (version < 15) {
530 db.beginTransaction();
531 try {
532 // Insert new column for holding update timestamp
533 db.execSQL("ALTER TABLE favorites " +
534 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
535 db.execSQL("ALTER TABLE workspaceScreens " +
536 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
537 db.setTransactionSuccessful();
538 version = 15;
539 } catch (SQLException ex) {
540 // Old version remains, which means we wipe old data
541 Log.e(TAG, ex.getMessage(), ex);
542 } finally {
543 db.endTransaction();
544 }
545 }
546
Chris Wrenf4d08112014-01-16 18:13:56 -0500547
548 if (version < 16) {
549 db.beginTransaction();
550 try {
551 // Insert new column for holding restore status
552 db.execSQL("ALTER TABLE favorites " +
553 "ADD COLUMN restored INTEGER NOT NULL DEFAULT 0;");
554 db.setTransactionSuccessful();
555 version = 16;
556 } catch (SQLException ex) {
557 // Old version remains, which means we wipe old data
558 Log.e(TAG, ex.getMessage(), ex);
559 } finally {
560 db.endTransaction();
561 }
562 }
563
Adam Cohen71e03b92014-02-21 14:09:53 -0800564 if (version < 17) {
565 // We use the db version upgrade here to identify users who may not have seen
566 // clings yet (because they weren't available), but for whom the clings are now
567 // available (tablet users). Because one of the possible cling flows (migration)
568 // is very destructive (wipes out workspaces), we want to prevent this from showing
569 // until clear data. We do so by marking that the clings have been shown.
570 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
571 version = 17;
572 }
573
Adam Cohen119285e2014-04-02 16:59:08 -0700574 if (version < 18) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700575 // No-op
576 version = 18;
577 }
578
579 if (version < 19) {
Adam Cohen119285e2014-04-02 16:59:08 -0700580 // Due to a data loss bug, some users may have items associated with screen ids
581 // which no longer exist. Since this can cause other problems, and since the user
582 // will never see these items anyway, we use database upgrade as an opportunity to
583 // clean things up.
Adam Cohenf9c14de2014-04-17 18:20:45 -0700584 removeOrphanedItems(db);
585 version = 19;
Adam Cohen119285e2014-04-02 16:59:08 -0700586 }
587
Kenny Guyed131872014-04-30 03:02:21 +0100588 if (version < 20) {
589 // Add userId column
590 if (addProfileColumn(db)) {
591 version = 20;
592 }
593 // else old version remains, which means we wipe old data
594 }
595
Sunny Goyal08f72612015-01-05 13:41:43 -0800596 if (version < 21) {
597 if (updateFolderItemsRank(db, true)) {
598 version = 21;
599 }
600 }
601
Sunny Goyal633325c2015-02-25 10:46:34 -0800602 if (version == 21) {
603 // Recreate workspace table with screen id a primary key
604 if (recreateWorkspaceTable(db)) {
605 version = 22;
606 }
607 }
608
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609 if (version != DATABASE_VERSION) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800610 Log.w(TAG, "Destroying all old data.");
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800611 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800612 }
613 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800614
Adam Cohen9b1d0622014-05-21 19:01:57 -0700615 @Override
616 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
617 // This shouldn't happen -- throw our hands up in the air and start over.
618 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
619 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700620 createEmptyDB(db);
621 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700622
Sunny Goyal42de82f2014-09-26 22:09:29 -0700623
624 /**
625 * Clears all the data for a fresh start.
626 */
627 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700628 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
629 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
630 onCreate(db);
631 }
632
Sunny Goyal633325c2015-02-25 10:46:34 -0800633 /**
634 * Recreates workspace table and migrates data to the new table.
635 */
636 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
637 db.beginTransaction();
638 try {
639 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
640 new String[] {LauncherSettings.WorkspaceScreens._ID},
641 null, null, null, null,
642 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
643 ArrayList<Long> sortedIDs = new ArrayList<Long>();
644 long maxId = 0;
645 try {
646 while (c.moveToNext()) {
647 Long id = c.getLong(0);
648 if (!sortedIDs.contains(id)) {
649 sortedIDs.add(id);
650 maxId = Math.max(maxId, id);
651 }
652 }
653 } finally {
654 c.close();
655 }
656
657 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
658 addWorkspacesTable(db);
659
660 // Add all screen ids back
661 int total = sortedIDs.size();
662 for (int i = 0; i < total; i++) {
663 ContentValues values = new ContentValues();
664 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
665 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
666 addModifiedTime(values);
667 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
668 }
669 db.setTransactionSuccessful();
670 mMaxScreenId = maxId;
671 } catch (SQLException ex) {
672 // Old version remains, which means we wipe old data
673 Log.e(TAG, ex.getMessage(), ex);
674 return false;
675 } finally {
676 db.endTransaction();
677 }
678 return true;
679 }
680
Sunny Goyal08f72612015-01-05 13:41:43 -0800681 private boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
682 db.beginTransaction();
683 try {
684 if (addRankColumn) {
685 // Insert new column for holding rank
686 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
687 }
688
689 // Get a map for folder ID to folder width
690 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
691 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
692 + " GROUP BY container;",
693 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
694
695 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800696 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
697 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800698 new Object[] {c.getLong(1) + 1, c.getLong(0)});
699 }
700
701 c.close();
702 db.setTransactionSuccessful();
703 } catch (SQLException ex) {
704 // Old version remains, which means we wipe old data
705 Log.e(TAG, ex.getMessage(), ex);
706 return false;
707 } finally {
708 db.endTransaction();
709 }
710 return true;
711 }
712
Kenny Guyed131872014-04-30 03:02:21 +0100713 private boolean addProfileColumn(SQLiteDatabase db) {
714 db.beginTransaction();
715 try {
716 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
717 // Default to the serial number of this user, for older
718 // shortcuts.
719 long userSerialNumber = userManager.getSerialNumberForUser(
720 UserHandleCompat.myUserHandle());
721 // Insert new column for holding user serial number
722 db.execSQL("ALTER TABLE favorites " +
723 "ADD COLUMN profileId INTEGER DEFAULT "
724 + userSerialNumber + ";");
725 db.setTransactionSuccessful();
726 } catch (SQLException ex) {
727 // Old version remains, which means we wipe old data
728 Log.e(TAG, ex.getMessage(), ex);
729 return false;
730 } finally {
731 db.endTransaction();
732 }
733 return true;
734 }
735
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700736 // Generates a new ID to use for an object in your database. This method should be only
737 // called from the main UI thread. As an exception, we do call it when we call the
738 // constructor from the worker thread; however, this doesn't extend until after the
739 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
740 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700741 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700742 public long generateNewItemId() {
743 if (mMaxItemId < 0) {
744 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700745 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700746 mMaxItemId += 1;
747 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700748 }
749
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700750 @Override
751 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
752 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
753 }
754
Winson Chungc763c4e2013-07-19 13:49:06 -0700755 public void updateMaxItemId(long id) {
756 mMaxItemId = id + 1;
757 }
758
Chris Wren5dee7af2013-12-20 17:22:11 -0500759 public void checkId(String table, ContentValues values) {
760 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
761 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
762 mMaxScreenId = Math.max(id, mMaxScreenId);
763 } else {
764 mMaxItemId = Math.max(id, mMaxItemId);
765 }
766 }
767
Adam Cohendcd297f2013-06-18 13:13:40 -0700768 private long initializeMaxItemId(SQLiteDatabase db) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700769 Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
770
771 // get the result
772 final int maxIdIndex = 0;
773 long id = -1;
774 if (c != null && c.moveToNext()) {
775 id = c.getLong(maxIdIndex);
776 }
Michael Jurka5130e402011-10-13 04:55:35 -0700777 if (c != null) {
778 c.close();
779 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700780
781 if (id == -1) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700782 throw new RuntimeException("Error: could not query max item id");
783 }
784
785 return id;
786 }
787
788 // Generates a new ID to use for an workspace screen in your database. This method
789 // should be only called from the main UI thread. As an exception, we do call it when we
790 // call the constructor from the worker thread; however, this doesn't extend until after the
791 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
792 // after that point
793 public long generateNewScreenId() {
794 if (mMaxScreenId < 0) {
795 throw new RuntimeException("Error: max screen id was not initialized");
796 }
797 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800798 // Log to disk
799 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700800 return mMaxScreenId;
801 }
802
803 public void updateMaxScreenId(long maxScreenId) {
Winson Chunga90303b2013-11-15 13:05:06 -0800804 // Log to disk
805 Launcher.addDumpLog(TAG, "11683562 - updateMaxScreenId(): " + maxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700806 mMaxScreenId = maxScreenId;
807 }
808
809 private long initializeMaxScreenId(SQLiteDatabase db) {
810 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens._ID + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
811
812 // get the result
813 final int maxIdIndex = 0;
814 long id = -1;
815 if (c != null && c.moveToNext()) {
816 id = c.getLong(maxIdIndex);
817 }
818 if (c != null) {
819 c.close();
820 }
821
822 if (id == -1) {
823 throw new RuntimeException("Error: could not query max screen id");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700824 }
825
Winson Chunga90303b2013-11-15 13:05:06 -0800826 // Log to disk
827 Launcher.addDumpLog(TAG, "11683562 - initializeMaxScreenId(): " + id, true);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700828 return id;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800829 }
830
Adam Cohena043fa82014-07-23 14:49:38 -0700831 private boolean initializeExternalAdd(ContentValues values) {
832 // 1. Ensure that externally added items have a valid item id
833 long id = generateNewItemId();
834 values.put(LauncherSettings.Favorites._ID, id);
835
836 // 2. In the case of an app widget, and if no app widget id is specified, we
837 // attempt allocate and bind the widget.
838 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
839 if (itemType != null &&
840 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
841 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
842
843 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
844 ComponentName cn = ComponentName.unflattenFromString(
845 values.getAsString(Favorites.APPWIDGET_PROVIDER));
846
847 if (cn != null) {
848 try {
849 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700850 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700851 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700852 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700853 }
854 } catch (RuntimeException e) {
855 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700856 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700857 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700858 } else {
859 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700860 }
861 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700862
863 // Add screen id if not present
864 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
865 if (!addScreenIdIfNecessary(screenId)) {
866 return false;
867 }
Adam Cohena043fa82014-07-23 14:49:38 -0700868 return true;
869 }
870
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700871 // Returns true of screen id exists, or if successfully added
872 private boolean addScreenIdIfNecessary(long screenId) {
873 if (!hasScreenId(screenId)) {
874 int rank = getMaxScreenRank() + 1;
875
876 ContentValues v = new ContentValues();
877 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
878 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
879 if (dbInsertAndCheck(this, getWritableDatabase(),
880 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
881 return false;
882 }
883 }
884 return true;
885 }
886
887 private boolean hasScreenId(long screenId) {
888 SQLiteDatabase db = getWritableDatabase();
889 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
890 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
891 if (c != null) {
892 int count = c.getCount();
893 c.close();
894 return count > 0;
895 } else {
896 return false;
897 }
898 }
899
900 private int getMaxScreenRank() {
901 SQLiteDatabase db = getWritableDatabase();
902 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
903 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
904
905 // get the result
906 final int maxRankIndex = 0;
907 int rank = -1;
908 if (c != null && c.moveToNext()) {
909 rank = c.getInt(maxRankIndex);
910 }
911 if (c != null) {
912 c.close();
913 }
914
915 return rank;
916 }
917
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700918 private int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700919 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700920 // TODO: Use multiple loaders with fall-back and transaction.
921 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700922
923 // Add the screens specified by the items above
924 Collections.sort(screenIds);
925 int rank = 0;
926 ContentValues values = new ContentValues();
927 for (Long id : screenIds) {
928 values.clear();
929 values.put(LauncherSettings.WorkspaceScreens._ID, id);
930 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
931 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
932 throw new RuntimeException("Failed initialize screen table"
933 + "from default layout");
934 }
935 rank++;
936 }
937
938 // Ensure that the max ids are initialized
939 mMaxItemId = initializeMaxItemId(db);
940 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700941
Adam Cohen71483f42014-05-15 14:04:01 -0700942 return count;
943 }
944
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700945 private void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500946 final ContentResolver resolver = mContext.getContentResolver();
947 Cursor c = null;
948 int count = 0;
949 int curScreen = 0;
950
951 try {
952 c = resolver.query(uri, null, null, null, "title ASC");
953 } catch (Exception e) {
954 // Ignore
955 }
956
Dan Sandlerd5024042014-01-09 15:01:33 -0500957 // We already have a favorites database in the old provider
958 if (c != null) {
959 try {
960 if (c.getCount() > 0) {
961 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
962 final int intentIndex
963 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
964 final int titleIndex
965 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
966 final int iconTypeIndex
967 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
968 final int iconIndex
969 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
970 final int iconPackageIndex
971 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
972 final int iconResourceIndex
973 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
974 final int containerIndex
975 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
976 final int itemTypeIndex
977 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
978 final int screenIndex
979 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
980 final int cellXIndex
981 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
982 final int cellYIndex
983 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
984 final int uriIndex
985 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
986 final int displayModeIndex
987 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100988 final int profileIndex
989 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500990
991 int i = 0;
992 int curX = 0;
993 int curY = 0;
994
995 final LauncherAppState app = LauncherAppState.getInstance();
996 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
997 final int width = (int) grid.numColumns;
998 final int height = (int) grid.numRows;
999 final int hotseatWidth = (int) grid.numHotseatIcons;
1000
1001 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1002
Adam Cohen72960972014-01-15 18:13:55 -08001003 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1004 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001005 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001006
1007 while (c.moveToNext()) {
1008 final int itemType = c.getInt(itemTypeIndex);
1009 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1010 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1011 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1012 continue;
1013 }
1014
1015 final int cellX = c.getInt(cellXIndex);
1016 final int cellY = c.getInt(cellYIndex);
1017 final int screen = c.getInt(screenIndex);
1018 int container = c.getInt(containerIndex);
1019 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001020
1021 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1022 UserHandleCompat userHandle;
1023 final long userSerialNumber;
1024 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1025 userSerialNumber = c.getInt(profileIndex);
1026 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1027 } else {
1028 // Default to the serial number of this user, for older
1029 // shortcuts.
1030 userHandle = UserHandleCompat.myUserHandle();
1031 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1032 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001033
1034 if (userHandle == null) {
1035 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1036 continue;
1037 }
1038
Dan Sandlerd5024042014-01-09 15:01:33 -05001039 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001040 + c.getString(titleIndex) + "\" ("
1041 + cellX + "," + cellY + "@"
1042 + LauncherSettings.Favorites.containerToString(container)
1043 + "/" + screen
1044 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001045
1046 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001047
1048 final Intent intent;
1049 final ComponentName cn;
1050 try {
1051 intent = Intent.parseUri(intentStr, 0);
1052 } catch (URISyntaxException e) {
1053 // bogus intent?
1054 Launcher.addDumpLog(TAG,
1055 "skipping invalid intent uri", true);
1056 continue;
1057 }
1058
1059 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001060 if (TextUtils.isEmpty(intentStr)) {
1061 // no intent? no icon
1062 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1063 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001064 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001065 !LauncherModel.isValidPackageActivity(mContext, cn,
1066 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001067 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001068 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001069 "no longer exists.", true);
1070 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001071 } else if (container ==
1072 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1073 // Dedupe icons directly on the workspace
1074
Adam Cohen556f6132014-01-15 15:18:08 -08001075 // Canonicalize
1076 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001077 // does not, so we clear that out to keep them the same.
1078 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001079 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001080 int flags = intent.getFlags();
1081 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001082 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001083 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001084 if (seenIntents.contains(key)) {
1085 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001086 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001087 } else {
1088 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001089 }
1090 }
1091 }
1092
1093 ContentValues values = new ContentValues(c.getColumnCount());
1094 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1095 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1096 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1097 values.put(LauncherSettings.Favorites.ICON_TYPE,
1098 c.getInt(iconTypeIndex));
1099 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1100 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1101 c.getString(iconPackageIndex));
1102 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1103 c.getString(iconResourceIndex));
1104 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1105 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1106 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1107 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1108 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001109 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001110
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001111 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1112 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001113 }
1114
1115 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1116 // In a folder or in the hotseat, preserve position
1117 values.put(LauncherSettings.Favorites.SCREEN, screen);
1118 values.put(LauncherSettings.Favorites.CELLX, cellX);
1119 values.put(LauncherSettings.Favorites.CELLY, cellY);
1120 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001121 // For items contained directly on one of the workspace screen,
1122 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001123 }
1124
1125 values.put(LauncherSettings.Favorites.CONTAINER, container);
1126
Adam Cohen72960972014-01-15 18:13:55 -08001127 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1128 shortcuts.add(values);
1129 } else {
1130 folders.add(values);
1131 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001132 }
1133
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001134 // Now that we have all the hotseat icons, let's go through them left-right
1135 // and assign valid locations for them in the new hotseat
1136 final int N = hotseat.size();
1137 for (int idx=0; idx<N; idx++) {
1138 int hotseatX = hotseat.keyAt(idx);
1139 ContentValues values = hotseat.valueAt(idx);
1140
1141 if (hotseatX == grid.hotseatAllAppsRank) {
1142 // let's drop this in the next available hole in the hotseat
1143 while (++hotseatX < hotseatWidth) {
1144 if (hotseat.get(hotseatX) == null) {
1145 // found a spot! move it here
1146 values.put(LauncherSettings.Favorites.SCREEN,
1147 hotseatX);
1148 break;
1149 }
1150 }
1151 }
1152 if (hotseatX >= hotseatWidth) {
1153 // no room for you in the hotseat? it's off to the desktop with you
1154 values.put(LauncherSettings.Favorites.CONTAINER,
1155 Favorites.CONTAINER_DESKTOP);
1156 }
1157 }
1158
Adam Cohen72960972014-01-15 18:13:55 -08001159 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1160 // Folders first
1161 allItems.addAll(folders);
1162 // Then shortcuts
1163 allItems.addAll(shortcuts);
1164
1165 // Layout all the folders
1166 for (ContentValues values: allItems) {
1167 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1168 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1169 // Hotseat items and folder items have already had their
1170 // location information set. Nothing to be done here.
1171 continue;
1172 }
1173 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1174 values.put(LauncherSettings.Favorites.CELLX, curX);
1175 values.put(LauncherSettings.Favorites.CELLY, curY);
1176 curX = (curX + 1) % width;
1177 if (curX == 0) {
1178 curY = (curY + 1);
1179 }
1180 // Leave the last row of icons blank on every screen
1181 if (curY == height - 1) {
1182 curScreen = (int) generateNewScreenId();
1183 curY = 0;
1184 }
1185 }
1186
1187 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001188 db.beginTransaction();
1189 try {
Adam Cohen72960972014-01-15 18:13:55 -08001190 for (ContentValues row: allItems) {
1191 if (row == null) continue;
1192 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001193 < 0) {
1194 return;
1195 } else {
1196 count++;
1197 }
1198 }
1199 db.setTransactionSuccessful();
1200 } finally {
1201 db.endTransaction();
1202 }
1203 }
1204
1205 db.beginTransaction();
1206 try {
1207 for (i=0; i<=curScreen; i++) {
1208 final ContentValues values = new ContentValues();
1209 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1210 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1211 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1212 < 0) {
1213 return;
1214 }
1215 }
1216 db.setTransactionSuccessful();
1217 } finally {
1218 db.endTransaction();
1219 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001220
1221 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001222 }
1223 } finally {
1224 c.close();
1225 }
1226 }
1227
1228 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1229 + (curScreen+1) + " screens", true);
1230
1231 // ensure that new screens are created to hold these icons
1232 setFlagJustLoadedOldDb();
1233
1234 // Update max IDs; very important since we just grabbed IDs from another database
1235 mMaxItemId = initializeMaxItemId(db);
1236 mMaxScreenId = initializeMaxScreenId(db);
1237 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1238 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001239 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001240
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001241 static class SqlArguments {
1242 public final String table;
1243 public final String where;
1244 public final String[] args;
1245
1246 SqlArguments(Uri url, String where, String[] args) {
1247 if (url.getPathSegments().size() == 1) {
1248 this.table = url.getPathSegments().get(0);
1249 this.where = where;
1250 this.args = args;
1251 } else if (url.getPathSegments().size() != 2) {
1252 throw new IllegalArgumentException("Invalid URI: " + url);
1253 } else if (!TextUtils.isEmpty(where)) {
1254 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1255 } else {
1256 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001257 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001258 this.args = null;
1259 }
1260 }
1261
1262 SqlArguments(Uri url) {
1263 if (url.getPathSegments().size() == 1) {
1264 table = url.getPathSegments().get(0);
1265 where = null;
1266 args = null;
1267 } else {
1268 throw new IllegalArgumentException("Invalid URI: " + url);
1269 }
1270 }
1271 }
Adam Cohen72960972014-01-15 18:13:55 -08001272}