blob: 1f59533cc19d6e8cc32a0263af6be4479ec1df28 [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
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070041import android.os.Build;
42import android.os.Bundle;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080043import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070044import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070045import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050047import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070048
Sunny Goyal0fe505b2014-08-06 09:55:36 -070049import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
50import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010051import com.android.launcher3.compat.UserHandleCompat;
52import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040053import com.android.launcher3.config.ProviderConfig;
Adam Cohen091440a2015-03-18 14:16:05 -070054import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070055
Dan Sandlerd5024042014-01-09 15:01:33 -050056import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070057import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070058import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070059import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080063 private static final String TAG = "Launcher.LauncherProvider";
64 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
Sunny Goyal5d85c442015-03-10 13:14:47 -070066 private static final int DATABASE_VERSION = 23;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067
Adam Cohene25af792013-06-06 23:08:25 -070068 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040069 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070070
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070072 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080073 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
Adam Cohena043fa82014-07-23 14:49:38 -070075 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
76
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070077 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
78
Anjali Koppal67e7cae2014-03-13 12:14:12 -070079 private LauncherProviderChangeListener mListener;
80
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070081 /**
Romain Guy73b979d2009-06-09 12:57:21 -070082 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070083 * {@link AppWidgetHost#deleteHost()} is called during database creation.
84 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
85 */
86 static final Uri CONTENT_APPWIDGET_RESET_URI =
87 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070088
Michael Jurkaa8c760d2011-04-28 14:59:33 -070089 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
91 @Override
92 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040093 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080094 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040095 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080096 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040097 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 return true;
99 }
100
Winson Chung0b560dd2014-01-21 13:00:26 -0800101 public boolean wasNewDbCreated() {
102 return mOpenHelper.wasNewDbCreated();
103 }
104
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700105 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
106 mListener = listener;
107 }
108
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109 @Override
110 public String getType(Uri uri) {
111 SqlArguments args = new SqlArguments(uri, null, null);
112 if (TextUtils.isEmpty(args.where)) {
113 return "vnd.android.cursor.dir/" + args.table;
114 } else {
115 return "vnd.android.cursor.item/" + args.table;
116 }
117 }
118
119 @Override
120 public Cursor query(Uri uri, String[] projection, String selection,
121 String[] selectionArgs, String sortOrder) {
122
123 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
124 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
125 qb.setTables(args.table);
126
Romain Guy73b979d2009-06-09 12:57:21 -0700127 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
129 result.setNotificationUri(getContext().getContentResolver(), uri);
130
131 return result;
132 }
133
Adam Cohen091440a2015-03-18 14:16:05 -0700134 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700135 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500136 if (values == null) {
137 throw new RuntimeException("Error: attempting to insert null values");
138 }
Adam Cohen71483f42014-05-15 14:04:01 -0700139 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 throw new RuntimeException("Error: attempting to add item without specifying an id");
141 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500142 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700143 return db.insert(table, nullColumnHack, values);
144 }
145
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800146 @Override
147 public Uri insert(Uri uri, ContentValues initialValues) {
148 SqlArguments args = new SqlArguments(uri);
149
Adam Cohena043fa82014-07-23 14:49:38 -0700150 // In very limited cases, we support system|signature permission apps to add to the db
151 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700152 final boolean isExternalAll = externalAdd != null && "true".equals(externalAdd);
153 if (isExternalAll) {
Adam Cohena043fa82014-07-23 14:49:38 -0700154 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
155 return null;
156 }
157 }
158
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400160 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800162 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163
164 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700165 notifyListeners();
166
167 if (isExternalAll) {
168 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
169 if (app != null) {
170 app.reloadWorkspace();
171 }
172 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173
174 return uri;
175 }
176
Adam Cohena043fa82014-07-23 14:49:38 -0700177
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178 @Override
179 public int bulkInsert(Uri uri, ContentValues[] values) {
180 SqlArguments args = new SqlArguments(uri);
181
182 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
183 db.beginTransaction();
184 try {
185 int numValues = values.length;
186 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400187 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700188 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
189 return 0;
190 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 }
192 db.setTransactionSuccessful();
193 } finally {
194 db.endTransaction();
195 }
196
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700197 notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198 return values.length;
199 }
200
201 @Override
Yura085c8532014-02-11 15:15:29 +0000202 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
203 throws OperationApplicationException {
204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
205 db.beginTransaction();
206 try {
207 ContentProviderResult[] result = super.applyBatch(operations);
208 db.setTransactionSuccessful();
209 return result;
210 } finally {
211 db.endTransaction();
212 }
213 }
214
215 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 public int delete(Uri uri, String selection, String[] selectionArgs) {
217 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
218
219 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
220 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700221 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222
223 return count;
224 }
225
226 @Override
227 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
228 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
229
Chris Wren1ada10d2013-09-13 18:01:38 -0400230 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
232 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700233 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234
235 return count;
236 }
237
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700238 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400239 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400240 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700241 if (mListener != null) {
242 mListener.onLauncherProviderChange();
243 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400244 }
245
Adam Cohen091440a2015-03-18 14:16:05 -0700246 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400247 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800248 }
249
Adam Cohendcd297f2013-06-18 13:13:40 -0700250 public long generateNewItemId() {
251 return mOpenHelper.generateNewItemId();
252 }
253
Winson Chungc763c4e2013-07-19 13:49:06 -0700254 public void updateMaxItemId(long id) {
255 mOpenHelper.updateMaxItemId(id);
256 }
257
Adam Cohendcd297f2013-06-18 13:13:40 -0700258 public long generateNewScreenId() {
259 return mOpenHelper.generateNewScreenId();
260 }
261
Brian Muramatsu5524b492012-10-02 16:55:54 -0700262 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700263 * Clears all the data for a fresh start.
264 */
265 synchronized public void createEmptyDB() {
266 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
267 }
268
Sunny Goyal33d44382014-10-16 09:24:19 -0700269 public void clearFlagEmptyDbCreated() {
270 String spKey = LauncherAppState.getSharedPreferencesKey();
271 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
272 .edit()
273 .remove(EMPTY_DATABASE_CREATED)
274 .commit();
275 }
276
Sunny Goyal42de82f2014-09-26 22:09:29 -0700277 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700278 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700279 * 1) From the app restrictions
280 * 2) From a package provided by play store
281 * 3) From a partner configuration APK, already in the system image
282 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700283 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700284 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400285 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700286 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700287
Winson Chungc763c4e2013-07-19 13:49:06 -0700288 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500289 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200290
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700291 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
292 if (loader == null) {
293 loader = AutoInstallsLayout.get(getContext(),
294 mOpenHelper.mAppWidgetHost, mOpenHelper);
295 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700296 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700297 final Partner partner = Partner.get(getContext().getPackageManager());
298 if (partner != null && partner.hasDefaultLayout()) {
299 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700300 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700301 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700302 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700303 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
304 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700305 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700306 }
307 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700308
Sunny Goyal9d219682014-10-23 14:21:02 -0700309 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700310 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700311 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700312 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800313
314 // There might be some partially restored DB items, due to buggy restore logic in
315 // previous versions of launcher.
316 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700317 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700318 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
319 && usingExternallyProvidedLayout) {
320 // Unable to load external layout. Cleanup and load the internal layout.
321 createEmptyDB();
322 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
323 getDefaultLayoutParser());
324 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700325 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700326 }
327 }
328
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700329 /**
330 * Creates workspace loader from an XML resource listed in the app restrictions.
331 *
332 * @return the loader if the restrictions are set and the resource exists; null otherwise.
333 */
334 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
335 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
336 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
337 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
338 return null;
339 }
340
341 Context ctx = getContext();
342 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
343 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700344 if (bundle == null) {
345 return null;
346 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700347
Sunny Goyal35ca8732015-04-06 10:45:31 -0700348 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700349 if (packageName != null) {
350 try {
351 Resources targetResources = ctx.getPackageManager()
352 .getResourcesForApplication(packageName);
353 return AutoInstallsLayout.get(ctx, packageName, targetResources,
354 mOpenHelper.mAppWidgetHost, mOpenHelper);
355 } catch (NameNotFoundException e) {
356 Log.e(TAG, "Target package for restricted profile not found", e);
357 return null;
358 }
359 }
360 return null;
361 }
362
Sunny Goyal9d219682014-10-23 14:21:02 -0700363 private DefaultLayoutParser getDefaultLayoutParser() {
364 int defaultLayout = LauncherAppState.getInstance()
365 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
366 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
367 mOpenHelper, getContext().getResources(), defaultLayout);
368 }
369
Dan Sandlerd5024042014-01-09 15:01:33 -0500370 public void migrateLauncher2Shortcuts() {
371 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400372 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500373 }
374
Sunny Goyal08f72612015-01-05 13:41:43 -0800375 public void updateFolderItemsRank() {
376 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
377 }
378
Dan Sandlerd5024042014-01-09 15:01:33 -0500379 public void deleteDatabase() {
380 // Are you sure? (y/n)
381 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500382 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500383 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500384 if (dbFile.exists()) {
385 SQLiteDatabase.deleteDatabase(dbFile);
386 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500387 mOpenHelper = new DatabaseHelper(getContext());
388 }
389
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700390 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800391 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700392 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700393 private long mMaxItemId = -1;
394 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395
Winson Chung0b560dd2014-01-21 13:00:26 -0800396 private boolean mNewDbCreated = false;
397
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800398 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100399 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800400 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700401 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700402
403 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
404 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700405 if (mMaxItemId == -1) {
406 mMaxItemId = initializeMaxItemId(getWritableDatabase());
407 }
408 if (mMaxScreenId == -1) {
409 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700410 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800411 }
412
Winson Chung0b560dd2014-01-21 13:00:26 -0800413 public boolean wasNewDbCreated() {
414 return mNewDbCreated;
415 }
416
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700417 /**
418 * Send notification that we've deleted the {@link AppWidgetHost},
419 * probably as part of the initial database creation. The receiver may
420 * want to re-call {@link AppWidgetHost#startListening()} to ensure
421 * callbacks are correctly set.
422 */
423 private void sendAppWidgetResetNotify() {
424 final ContentResolver resolver = mContext.getContentResolver();
425 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
426 }
427
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800428 @Override
429 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800430 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700431
Adam Cohendcd297f2013-06-18 13:13:40 -0700432 mMaxItemId = 1;
433 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800434 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700435
Kenny Guyed131872014-04-30 03:02:21 +0100436 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
437 long userSerialNumber = userManager.getSerialNumberForUser(
438 UserHandleCompat.myUserHandle());
439
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800440 db.execSQL("CREATE TABLE favorites (" +
441 "_id INTEGER PRIMARY KEY," +
442 "title TEXT," +
443 "intent TEXT," +
444 "container INTEGER," +
445 "screen INTEGER," +
446 "cellX INTEGER," +
447 "cellY INTEGER," +
448 "spanX INTEGER," +
449 "spanY INTEGER," +
450 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700451 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800452 "isShortcut INTEGER," +
453 "iconType INTEGER," +
454 "iconPackage TEXT," +
455 "iconResource TEXT," +
456 "icon BLOB," +
457 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400458 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400459 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500460 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100461 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800462 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700463 "rank INTEGER NOT NULL DEFAULT 0," +
464 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700466 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800467
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700468 // Database was just created, so wipe any previous widgets
469 if (mAppWidgetHost != null) {
470 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700471 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700473
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800474 // Fresh and clean launcher DB.
475 mMaxItemId = initializeMaxItemId(db);
476 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477 }
478
Adam Cohendcd297f2013-06-18 13:13:40 -0700479 private void addWorkspacesTable(SQLiteDatabase db) {
480 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800481 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400482 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
483 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700484 ");");
485 }
486
Adam Cohen119285e2014-04-02 16:59:08 -0700487 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700488 // Delete items directly on the workspace who's screen id doesn't exist
489 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
490 // AND container = -100"
491 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
492 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700493 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700494 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
495 " AND " +
496 LauncherSettings.Favorites.CONTAINER + " = " +
497 LauncherSettings.Favorites.CONTAINER_DESKTOP;
498 db.execSQL(removeOrphanedDesktopItems);
499
500 // Delete items contained in folders which no longer exist (after above statement)
501 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
502 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
503 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
504 " WHERE " +
505 LauncherSettings.Favorites.CONTAINER + " <> " +
506 LauncherSettings.Favorites.CONTAINER_DESKTOP +
507 " AND "
508 + LauncherSettings.Favorites.CONTAINER + " <> " +
509 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
510 " AND "
511 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
512 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
513 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
514 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
515 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700516 }
517
Winson Chungc763c4e2013-07-19 13:49:06 -0700518 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400519 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700520 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800521 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700522 }
523
Winson Chungc763c4e2013-07-19 13:49:06 -0700524 private void setFlagEmptyDbCreated() {
525 String spKey = LauncherAppState.getSharedPreferencesKey();
526 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800527 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700528 }
529
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800530 @Override
531 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700532 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800533 switch (oldVersion) {
534 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800535 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800536 case 12: {
537 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
538 // to persist workspace screens and their relative order.
539 mMaxScreenId = 0;
540 addWorkspacesTable(db);
541 }
542 case 13: {
543 db.beginTransaction();
544 try {
545 // Insert new column for holding widget provider name
546 db.execSQL("ALTER TABLE favorites " +
547 "ADD COLUMN appWidgetProvider TEXT;");
548 db.setTransactionSuccessful();
549 } catch (SQLException ex) {
550 Log.e(TAG, ex.getMessage(), ex);
551 // Old version remains, which means we wipe old data
552 break;
553 } finally {
554 db.endTransaction();
555 }
556 }
557 case 14: {
558 db.beginTransaction();
559 try {
560 // Insert new column for holding update timestamp
561 db.execSQL("ALTER TABLE favorites " +
562 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
563 db.execSQL("ALTER TABLE workspaceScreens " +
564 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
565 db.setTransactionSuccessful();
566 } catch (SQLException ex) {
567 Log.e(TAG, ex.getMessage(), ex);
568 // Old version remains, which means we wipe old data
569 break;
570 } finally {
571 db.endTransaction();
572 }
573 }
574 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700575 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800576 // Old version remains, which means we wipe old data
577 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800578 }
579 }
580 case 16: {
581 // We use the db version upgrade here to identify users who may not have seen
582 // clings yet (because they weren't available), but for whom the clings are now
583 // available (tablet users). Because one of the possible cling flows (migration)
584 // is very destructive (wipes out workspaces), we want to prevent this from showing
585 // until clear data. We do so by marking that the clings have been shown.
586 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
587 }
588 case 17: {
589 // No-op
590 }
591 case 18: {
592 // Due to a data loss bug, some users may have items associated with screen ids
593 // which no longer exist. Since this can cause other problems, and since the user
594 // will never see these items anyway, we use database upgrade as an opportunity to
595 // clean things up.
596 removeOrphanedItems(db);
597 }
598 case 19: {
599 // Add userId column
600 if (!addProfileColumn(db)) {
601 // Old version remains, which means we wipe old data
602 break;
603 }
604 }
605 case 20:
606 if (!updateFolderItemsRank(db, true)) {
607 break;
608 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800609 case 21:
610 // Recreate workspace table with screen id a primary key
611 if (!recreateWorkspaceTable(db)) {
612 break;
613 }
614 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700615 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
616 // Old version remains, which means we wipe old data
617 break;
618 }
619 }
620 case 23: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800621 // DB Upgraded successfully
622 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400623 }
624 }
625
Sunny Goyala2cc6242015-01-14 14:23:02 -0800626 // DB was not upgraded
627 Log.w(TAG, "Destroying all old data.");
628 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800630
Adam Cohen9b1d0622014-05-21 19:01:57 -0700631 @Override
632 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
633 // This shouldn't happen -- throw our hands up in the air and start over.
634 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
635 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700636 createEmptyDB(db);
637 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700638
Sunny Goyal42de82f2014-09-26 22:09:29 -0700639
640 /**
641 * Clears all the data for a fresh start.
642 */
643 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700644 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
645 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
646 onCreate(db);
647 }
648
Sunny Goyald2f38192015-02-25 10:46:34 -0800649 /**
650 * Recreates workspace table and migrates data to the new table.
651 */
652 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
653 db.beginTransaction();
654 try {
655 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
656 new String[] {LauncherSettings.WorkspaceScreens._ID},
657 null, null, null, null,
658 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
659 ArrayList<Long> sortedIDs = new ArrayList<Long>();
660 long maxId = 0;
661 try {
662 while (c.moveToNext()) {
663 Long id = c.getLong(0);
664 if (!sortedIDs.contains(id)) {
665 sortedIDs.add(id);
666 maxId = Math.max(maxId, id);
667 }
668 }
669 } finally {
670 c.close();
671 }
672
673 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
674 addWorkspacesTable(db);
675
676 // Add all screen ids back
677 int total = sortedIDs.size();
678 for (int i = 0; i < total; i++) {
679 ContentValues values = new ContentValues();
680 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
681 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
682 addModifiedTime(values);
683 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
684 }
685 db.setTransactionSuccessful();
686 mMaxScreenId = maxId;
687 } catch (SQLException ex) {
688 // Old version remains, which means we wipe old data
689 Log.e(TAG, ex.getMessage(), ex);
690 return false;
691 } finally {
692 db.endTransaction();
693 }
694 return true;
695 }
696
Adam Cohen091440a2015-03-18 14:16:05 -0700697 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800698 db.beginTransaction();
699 try {
700 if (addRankColumn) {
701 // Insert new column for holding rank
702 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
703 }
704
705 // Get a map for folder ID to folder width
706 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
707 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
708 + " GROUP BY container;",
709 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
710
711 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800712 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
713 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800714 new Object[] {c.getLong(1) + 1, c.getLong(0)});
715 }
716
717 c.close();
718 db.setTransactionSuccessful();
719 } catch (SQLException ex) {
720 // Old version remains, which means we wipe old data
721 Log.e(TAG, ex.getMessage(), ex);
722 return false;
723 } finally {
724 db.endTransaction();
725 }
726 return true;
727 }
728
Kenny Guyed131872014-04-30 03:02:21 +0100729 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700730 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
731 // Default to the serial number of this user, for older
732 // shortcuts.
733 long userSerialNumber = userManager.getSerialNumberForUser(
734 UserHandleCompat.myUserHandle());
735 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
736 }
737
738 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100739 db.beginTransaction();
740 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700741 db.execSQL("ALTER TABLE favorites ADD COLUMN "
742 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100743 db.setTransactionSuccessful();
744 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100745 Log.e(TAG, ex.getMessage(), ex);
746 return false;
747 } finally {
748 db.endTransaction();
749 }
750 return true;
751 }
752
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700753 // Generates a new ID to use for an object in your database. This method should be only
754 // called from the main UI thread. As an exception, we do call it when we call the
755 // constructor from the worker thread; however, this doesn't extend until after the
756 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
757 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700758 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700759 public long generateNewItemId() {
760 if (mMaxItemId < 0) {
761 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700762 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700763 mMaxItemId += 1;
764 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700765 }
766
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700767 @Override
768 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
769 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
770 }
771
Winson Chungc763c4e2013-07-19 13:49:06 -0700772 public void updateMaxItemId(long id) {
773 mMaxItemId = id + 1;
774 }
775
Chris Wren5dee7af2013-12-20 17:22:11 -0500776 public void checkId(String table, ContentValues values) {
777 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
778 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
779 mMaxScreenId = Math.max(id, mMaxScreenId);
780 } else {
781 mMaxItemId = Math.max(id, mMaxItemId);
782 }
783 }
784
Adam Cohendcd297f2013-06-18 13:13:40 -0700785 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800786 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700787 }
788
789 // Generates a new ID to use for an workspace screen in your database. This method
790 // should be only called from the main UI thread. As an exception, we do call it when we
791 // call the constructor from the worker thread; however, this doesn't extend until after the
792 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
793 // after that point
794 public long generateNewScreenId() {
795 if (mMaxScreenId < 0) {
796 throw new RuntimeException("Error: max screen id was not initialized");
797 }
798 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800799 // Log to disk
800 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 return mMaxScreenId;
802 }
803
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800805 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800806 }
807
Adam Cohen091440a2015-03-18 14:16:05 -0700808 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700809 // 1. Ensure that externally added items have a valid item id
810 long id = generateNewItemId();
811 values.put(LauncherSettings.Favorites._ID, id);
812
813 // 2. In the case of an app widget, and if no app widget id is specified, we
814 // attempt allocate and bind the widget.
815 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
816 if (itemType != null &&
817 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
818 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
819
820 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
821 ComponentName cn = ComponentName.unflattenFromString(
822 values.getAsString(Favorites.APPWIDGET_PROVIDER));
823
824 if (cn != null) {
825 try {
826 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700827 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700828 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700829 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700830 }
831 } catch (RuntimeException e) {
832 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700833 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700834 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700835 } else {
836 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700837 }
838 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700839
840 // Add screen id if not present
841 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
842 if (!addScreenIdIfNecessary(screenId)) {
843 return false;
844 }
Adam Cohena043fa82014-07-23 14:49:38 -0700845 return true;
846 }
847
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700848 // Returns true of screen id exists, or if successfully added
849 private boolean addScreenIdIfNecessary(long screenId) {
850 if (!hasScreenId(screenId)) {
851 int rank = getMaxScreenRank() + 1;
852
853 ContentValues v = new ContentValues();
854 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
855 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
856 if (dbInsertAndCheck(this, getWritableDatabase(),
857 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
858 return false;
859 }
860 }
861 return true;
862 }
863
864 private boolean hasScreenId(long screenId) {
865 SQLiteDatabase db = getWritableDatabase();
866 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
867 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
868 if (c != null) {
869 int count = c.getCount();
870 c.close();
871 return count > 0;
872 } else {
873 return false;
874 }
875 }
876
877 private int getMaxScreenRank() {
878 SQLiteDatabase db = getWritableDatabase();
879 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
880 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
881
882 // get the result
883 final int maxRankIndex = 0;
884 int rank = -1;
885 if (c != null && c.moveToNext()) {
886 rank = c.getInt(maxRankIndex);
887 }
888 if (c != null) {
889 c.close();
890 }
891
892 return rank;
893 }
894
Adam Cohen091440a2015-03-18 14:16:05 -0700895 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700896 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700897 // TODO: Use multiple loaders with fall-back and transaction.
898 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700899
900 // Add the screens specified by the items above
901 Collections.sort(screenIds);
902 int rank = 0;
903 ContentValues values = new ContentValues();
904 for (Long id : screenIds) {
905 values.clear();
906 values.put(LauncherSettings.WorkspaceScreens._ID, id);
907 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
908 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
909 throw new RuntimeException("Failed initialize screen table"
910 + "from default layout");
911 }
912 rank++;
913 }
914
915 // Ensure that the max ids are initialized
916 mMaxItemId = initializeMaxItemId(db);
917 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700918
Adam Cohen71483f42014-05-15 14:04:01 -0700919 return count;
920 }
921
Adam Cohen091440a2015-03-18 14:16:05 -0700922 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500923 final ContentResolver resolver = mContext.getContentResolver();
924 Cursor c = null;
925 int count = 0;
926 int curScreen = 0;
927
928 try {
929 c = resolver.query(uri, null, null, null, "title ASC");
930 } catch (Exception e) {
931 // Ignore
932 }
933
Dan Sandlerd5024042014-01-09 15:01:33 -0500934 // We already have a favorites database in the old provider
935 if (c != null) {
936 try {
937 if (c.getCount() > 0) {
938 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
939 final int intentIndex
940 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
941 final int titleIndex
942 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
943 final int iconTypeIndex
944 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
945 final int iconIndex
946 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
947 final int iconPackageIndex
948 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
949 final int iconResourceIndex
950 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
951 final int containerIndex
952 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
953 final int itemTypeIndex
954 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
955 final int screenIndex
956 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
957 final int cellXIndex
958 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
959 final int cellYIndex
960 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
961 final int uriIndex
962 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
963 final int displayModeIndex
964 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100965 final int profileIndex
966 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500967
968 int i = 0;
969 int curX = 0;
970 int curY = 0;
971
972 final LauncherAppState app = LauncherAppState.getInstance();
973 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
974 final int width = (int) grid.numColumns;
975 final int height = (int) grid.numRows;
976 final int hotseatWidth = (int) grid.numHotseatIcons;
977
978 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
979
Adam Cohen72960972014-01-15 18:13:55 -0800980 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
981 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500982 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500983
984 while (c.moveToNext()) {
985 final int itemType = c.getInt(itemTypeIndex);
986 if (itemType != Favorites.ITEM_TYPE_APPLICATION
987 && itemType != Favorites.ITEM_TYPE_SHORTCUT
988 && itemType != Favorites.ITEM_TYPE_FOLDER) {
989 continue;
990 }
991
992 final int cellX = c.getInt(cellXIndex);
993 final int cellY = c.getInt(cellYIndex);
994 final int screen = c.getInt(screenIndex);
995 int container = c.getInt(containerIndex);
996 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100997
998 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
999 UserHandleCompat userHandle;
1000 final long userSerialNumber;
1001 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1002 userSerialNumber = c.getInt(profileIndex);
1003 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1004 } else {
1005 // Default to the serial number of this user, for older
1006 // shortcuts.
1007 userHandle = UserHandleCompat.myUserHandle();
1008 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1009 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001010
1011 if (userHandle == null) {
1012 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1013 continue;
1014 }
1015
Dan Sandlerd5024042014-01-09 15:01:33 -05001016 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001017 + c.getString(titleIndex) + "\" ("
1018 + cellX + "," + cellY + "@"
1019 + LauncherSettings.Favorites.containerToString(container)
1020 + "/" + screen
1021 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001022
1023 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001024
1025 final Intent intent;
1026 final ComponentName cn;
1027 try {
1028 intent = Intent.parseUri(intentStr, 0);
1029 } catch (URISyntaxException e) {
1030 // bogus intent?
1031 Launcher.addDumpLog(TAG,
1032 "skipping invalid intent uri", true);
1033 continue;
1034 }
1035
1036 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001037 if (TextUtils.isEmpty(intentStr)) {
1038 // no intent? no icon
1039 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1040 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001041 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001042 !LauncherModel.isValidPackageActivity(mContext, cn,
1043 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001044 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001045 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001046 "no longer exists.", true);
1047 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001048 } else if (container ==
1049 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1050 // Dedupe icons directly on the workspace
1051
Adam Cohen556f6132014-01-15 15:18:08 -08001052 // Canonicalize
1053 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001054 // does not, so we clear that out to keep them the same.
1055 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001056 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001057 int flags = intent.getFlags();
1058 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001059 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001060 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001061 if (seenIntents.contains(key)) {
1062 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001063 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001064 } else {
1065 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001066 }
1067 }
1068 }
1069
1070 ContentValues values = new ContentValues(c.getColumnCount());
1071 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1072 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1073 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1074 values.put(LauncherSettings.Favorites.ICON_TYPE,
1075 c.getInt(iconTypeIndex));
1076 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1077 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1078 c.getString(iconPackageIndex));
1079 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1080 c.getString(iconResourceIndex));
1081 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1082 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1083 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1084 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1085 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001086 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001087
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001088 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1089 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001090 }
1091
1092 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1093 // In a folder or in the hotseat, preserve position
1094 values.put(LauncherSettings.Favorites.SCREEN, screen);
1095 values.put(LauncherSettings.Favorites.CELLX, cellX);
1096 values.put(LauncherSettings.Favorites.CELLY, cellY);
1097 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001098 // For items contained directly on one of the workspace screen,
1099 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001100 }
1101
1102 values.put(LauncherSettings.Favorites.CONTAINER, container);
1103
Adam Cohen72960972014-01-15 18:13:55 -08001104 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1105 shortcuts.add(values);
1106 } else {
1107 folders.add(values);
1108 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001109 }
1110
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001111 // Now that we have all the hotseat icons, let's go through them left-right
1112 // and assign valid locations for them in the new hotseat
1113 final int N = hotseat.size();
1114 for (int idx=0; idx<N; idx++) {
1115 int hotseatX = hotseat.keyAt(idx);
1116 ContentValues values = hotseat.valueAt(idx);
1117
1118 if (hotseatX == grid.hotseatAllAppsRank) {
1119 // let's drop this in the next available hole in the hotseat
1120 while (++hotseatX < hotseatWidth) {
1121 if (hotseat.get(hotseatX) == null) {
1122 // found a spot! move it here
1123 values.put(LauncherSettings.Favorites.SCREEN,
1124 hotseatX);
1125 break;
1126 }
1127 }
1128 }
1129 if (hotseatX >= hotseatWidth) {
1130 // no room for you in the hotseat? it's off to the desktop with you
1131 values.put(LauncherSettings.Favorites.CONTAINER,
1132 Favorites.CONTAINER_DESKTOP);
1133 }
1134 }
1135
Adam Cohen72960972014-01-15 18:13:55 -08001136 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1137 // Folders first
1138 allItems.addAll(folders);
1139 // Then shortcuts
1140 allItems.addAll(shortcuts);
1141
1142 // Layout all the folders
1143 for (ContentValues values: allItems) {
1144 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1145 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1146 // Hotseat items and folder items have already had their
1147 // location information set. Nothing to be done here.
1148 continue;
1149 }
1150 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1151 values.put(LauncherSettings.Favorites.CELLX, curX);
1152 values.put(LauncherSettings.Favorites.CELLY, curY);
1153 curX = (curX + 1) % width;
1154 if (curX == 0) {
1155 curY = (curY + 1);
1156 }
1157 // Leave the last row of icons blank on every screen
1158 if (curY == height - 1) {
1159 curScreen = (int) generateNewScreenId();
1160 curY = 0;
1161 }
1162 }
1163
1164 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001165 db.beginTransaction();
1166 try {
Adam Cohen72960972014-01-15 18:13:55 -08001167 for (ContentValues row: allItems) {
1168 if (row == null) continue;
1169 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001170 < 0) {
1171 return;
1172 } else {
1173 count++;
1174 }
1175 }
1176 db.setTransactionSuccessful();
1177 } finally {
1178 db.endTransaction();
1179 }
1180 }
1181
1182 db.beginTransaction();
1183 try {
1184 for (i=0; i<=curScreen; i++) {
1185 final ContentValues values = new ContentValues();
1186 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1187 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1188 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1189 < 0) {
1190 return;
1191 }
1192 }
1193 db.setTransactionSuccessful();
1194 } finally {
1195 db.endTransaction();
1196 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001197
1198 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001199 }
1200 } finally {
1201 c.close();
1202 }
1203 }
1204
1205 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1206 + (curScreen+1) + " screens", true);
1207
1208 // ensure that new screens are created to hold these icons
1209 setFlagJustLoadedOldDb();
1210
1211 // Update max IDs; very important since we just grabbed IDs from another database
1212 mMaxItemId = initializeMaxItemId(db);
1213 mMaxScreenId = initializeMaxScreenId(db);
1214 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1215 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001216 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001217
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001218 /**
1219 * @return the max _id in the provided table.
1220 */
Adam Cohen091440a2015-03-18 14:16:05 -07001221 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001222 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1223 // get the result
1224 long id = -1;
1225 if (c != null && c.moveToNext()) {
1226 id = c.getLong(0);
1227 }
1228 if (c != null) {
1229 c.close();
1230 }
1231
1232 if (id == -1) {
1233 throw new RuntimeException("Error: could not query max id in " + table);
1234 }
1235
1236 return id;
1237 }
1238
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001239 static class SqlArguments {
1240 public final String table;
1241 public final String where;
1242 public final String[] args;
1243
1244 SqlArguments(Uri url, String where, String[] args) {
1245 if (url.getPathSegments().size() == 1) {
1246 this.table = url.getPathSegments().get(0);
1247 this.where = where;
1248 this.args = args;
1249 } else if (url.getPathSegments().size() != 2) {
1250 throw new IllegalArgumentException("Invalid URI: " + url);
1251 } else if (!TextUtils.isEmpty(where)) {
1252 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1253 } else {
1254 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001255 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001256 this.args = null;
1257 }
1258 }
1259
1260 SqlArguments(Uri url) {
1261 if (url.getPathSegments().size() == 1) {
1262 table = url.getPathSegments().get(0);
1263 where = null;
1264 args = null;
1265 } else {
1266 throw new IllegalArgumentException("Invalid URI: " + url);
1267 }
1268 }
1269 }
Adam Cohen72960972014-01-15 18:13:55 -08001270}