blob: a23553a04fdb3aa0df7236518c4cd839d32c8e61 [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());
344 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
345
346 if (packageName != null) {
347 try {
348 Resources targetResources = ctx.getPackageManager()
349 .getResourcesForApplication(packageName);
350 return AutoInstallsLayout.get(ctx, packageName, targetResources,
351 mOpenHelper.mAppWidgetHost, mOpenHelper);
352 } catch (NameNotFoundException e) {
353 Log.e(TAG, "Target package for restricted profile not found", e);
354 return null;
355 }
356 }
357 return null;
358 }
359
Sunny Goyal9d219682014-10-23 14:21:02 -0700360 private DefaultLayoutParser getDefaultLayoutParser() {
361 int defaultLayout = LauncherAppState.getInstance()
362 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
363 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
364 mOpenHelper, getContext().getResources(), defaultLayout);
365 }
366
Dan Sandlerd5024042014-01-09 15:01:33 -0500367 public void migrateLauncher2Shortcuts() {
368 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400369 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500370 }
371
Sunny Goyal08f72612015-01-05 13:41:43 -0800372 public void updateFolderItemsRank() {
373 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
374 }
375
Dan Sandlerd5024042014-01-09 15:01:33 -0500376 public void deleteDatabase() {
377 // Are you sure? (y/n)
378 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500379 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500380 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500381 if (dbFile.exists()) {
382 SQLiteDatabase.deleteDatabase(dbFile);
383 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500384 mOpenHelper = new DatabaseHelper(getContext());
385 }
386
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700387 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800388 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700389 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700390 private long mMaxItemId = -1;
391 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800392
Winson Chung0b560dd2014-01-21 13:00:26 -0800393 private boolean mNewDbCreated = false;
394
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100396 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800397 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700398 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700399
400 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
401 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700402 if (mMaxItemId == -1) {
403 mMaxItemId = initializeMaxItemId(getWritableDatabase());
404 }
405 if (mMaxScreenId == -1) {
406 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700407 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800408 }
409
Winson Chung0b560dd2014-01-21 13:00:26 -0800410 public boolean wasNewDbCreated() {
411 return mNewDbCreated;
412 }
413
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700414 /**
415 * Send notification that we've deleted the {@link AppWidgetHost},
416 * probably as part of the initial database creation. The receiver may
417 * want to re-call {@link AppWidgetHost#startListening()} to ensure
418 * callbacks are correctly set.
419 */
420 private void sendAppWidgetResetNotify() {
421 final ContentResolver resolver = mContext.getContentResolver();
422 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
423 }
424
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 @Override
426 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800427 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700428
Adam Cohendcd297f2013-06-18 13:13:40 -0700429 mMaxItemId = 1;
430 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800431 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700432
Kenny Guyed131872014-04-30 03:02:21 +0100433 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
434 long userSerialNumber = userManager.getSerialNumberForUser(
435 UserHandleCompat.myUserHandle());
436
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800437 db.execSQL("CREATE TABLE favorites (" +
438 "_id INTEGER PRIMARY KEY," +
439 "title TEXT," +
440 "intent TEXT," +
441 "container INTEGER," +
442 "screen INTEGER," +
443 "cellX INTEGER," +
444 "cellY INTEGER," +
445 "spanX INTEGER," +
446 "spanY INTEGER," +
447 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700448 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800449 "isShortcut INTEGER," +
450 "iconType INTEGER," +
451 "iconPackage TEXT," +
452 "iconResource TEXT," +
453 "icon BLOB," +
454 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400455 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400456 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500457 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100458 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800459 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700460 "rank INTEGER NOT NULL DEFAULT 0," +
461 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800462 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700463 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800464
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700465 // Database was just created, so wipe any previous widgets
466 if (mAppWidgetHost != null) {
467 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700468 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700470
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800471 // Fresh and clean launcher DB.
472 mMaxItemId = initializeMaxItemId(db);
473 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474 }
475
Adam Cohendcd297f2013-06-18 13:13:40 -0700476 private void addWorkspacesTable(SQLiteDatabase db) {
477 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800478 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
480 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700481 ");");
482 }
483
Adam Cohen119285e2014-04-02 16:59:08 -0700484 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700485 // Delete items directly on the workspace who's screen id doesn't exist
486 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
487 // AND container = -100"
488 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
489 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700490 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700491 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
492 " AND " +
493 LauncherSettings.Favorites.CONTAINER + " = " +
494 LauncherSettings.Favorites.CONTAINER_DESKTOP;
495 db.execSQL(removeOrphanedDesktopItems);
496
497 // Delete items contained in folders which no longer exist (after above statement)
498 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
499 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
500 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
501 " WHERE " +
502 LauncherSettings.Favorites.CONTAINER + " <> " +
503 LauncherSettings.Favorites.CONTAINER_DESKTOP +
504 " AND "
505 + LauncherSettings.Favorites.CONTAINER + " <> " +
506 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
507 " AND "
508 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
509 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
510 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
511 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
512 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700513 }
514
Winson Chungc763c4e2013-07-19 13:49:06 -0700515 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400516 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700517 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800518 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700519 }
520
Winson Chungc763c4e2013-07-19 13:49:06 -0700521 private void setFlagEmptyDbCreated() {
522 String spKey = LauncherAppState.getSharedPreferencesKey();
523 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800524 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700525 }
526
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800527 @Override
528 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700529 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800530 switch (oldVersion) {
531 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800532 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800533 case 12: {
534 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
535 // to persist workspace screens and their relative order.
536 mMaxScreenId = 0;
537 addWorkspacesTable(db);
538 }
539 case 13: {
540 db.beginTransaction();
541 try {
542 // Insert new column for holding widget provider name
543 db.execSQL("ALTER TABLE favorites " +
544 "ADD COLUMN appWidgetProvider TEXT;");
545 db.setTransactionSuccessful();
546 } catch (SQLException ex) {
547 Log.e(TAG, ex.getMessage(), ex);
548 // Old version remains, which means we wipe old data
549 break;
550 } finally {
551 db.endTransaction();
552 }
553 }
554 case 14: {
555 db.beginTransaction();
556 try {
557 // Insert new column for holding update timestamp
558 db.execSQL("ALTER TABLE favorites " +
559 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
560 db.execSQL("ALTER TABLE workspaceScreens " +
561 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
562 db.setTransactionSuccessful();
563 } catch (SQLException ex) {
564 Log.e(TAG, ex.getMessage(), ex);
565 // Old version remains, which means we wipe old data
566 break;
567 } finally {
568 db.endTransaction();
569 }
570 }
571 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700572 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800573 // Old version remains, which means we wipe old data
574 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800575 }
576 }
577 case 16: {
578 // We use the db version upgrade here to identify users who may not have seen
579 // clings yet (because they weren't available), but for whom the clings are now
580 // available (tablet users). Because one of the possible cling flows (migration)
581 // is very destructive (wipes out workspaces), we want to prevent this from showing
582 // until clear data. We do so by marking that the clings have been shown.
583 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
584 }
585 case 17: {
586 // No-op
587 }
588 case 18: {
589 // Due to a data loss bug, some users may have items associated with screen ids
590 // which no longer exist. Since this can cause other problems, and since the user
591 // will never see these items anyway, we use database upgrade as an opportunity to
592 // clean things up.
593 removeOrphanedItems(db);
594 }
595 case 19: {
596 // Add userId column
597 if (!addProfileColumn(db)) {
598 // Old version remains, which means we wipe old data
599 break;
600 }
601 }
602 case 20:
603 if (!updateFolderItemsRank(db, true)) {
604 break;
605 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800606 case 21:
607 // Recreate workspace table with screen id a primary key
608 if (!recreateWorkspaceTable(db)) {
609 break;
610 }
611 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700612 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
613 // Old version remains, which means we wipe old data
614 break;
615 }
616 }
617 case 23: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800618 // DB Upgraded successfully
619 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400620 }
621 }
622
Sunny Goyala2cc6242015-01-14 14:23:02 -0800623 // DB was not upgraded
624 Log.w(TAG, "Destroying all old data.");
625 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800626 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800627
Adam Cohen9b1d0622014-05-21 19:01:57 -0700628 @Override
629 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
630 // This shouldn't happen -- throw our hands up in the air and start over.
631 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
632 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700633 createEmptyDB(db);
634 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700635
Sunny Goyal42de82f2014-09-26 22:09:29 -0700636
637 /**
638 * Clears all the data for a fresh start.
639 */
640 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700641 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
642 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
643 onCreate(db);
644 }
645
Sunny Goyald2f38192015-02-25 10:46:34 -0800646 /**
647 * Recreates workspace table and migrates data to the new table.
648 */
649 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
650 db.beginTransaction();
651 try {
652 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
653 new String[] {LauncherSettings.WorkspaceScreens._ID},
654 null, null, null, null,
655 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
656 ArrayList<Long> sortedIDs = new ArrayList<Long>();
657 long maxId = 0;
658 try {
659 while (c.moveToNext()) {
660 Long id = c.getLong(0);
661 if (!sortedIDs.contains(id)) {
662 sortedIDs.add(id);
663 maxId = Math.max(maxId, id);
664 }
665 }
666 } finally {
667 c.close();
668 }
669
670 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
671 addWorkspacesTable(db);
672
673 // Add all screen ids back
674 int total = sortedIDs.size();
675 for (int i = 0; i < total; i++) {
676 ContentValues values = new ContentValues();
677 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
678 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
679 addModifiedTime(values);
680 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
681 }
682 db.setTransactionSuccessful();
683 mMaxScreenId = maxId;
684 } catch (SQLException ex) {
685 // Old version remains, which means we wipe old data
686 Log.e(TAG, ex.getMessage(), ex);
687 return false;
688 } finally {
689 db.endTransaction();
690 }
691 return true;
692 }
693
Adam Cohen091440a2015-03-18 14:16:05 -0700694 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800695 db.beginTransaction();
696 try {
697 if (addRankColumn) {
698 // Insert new column for holding rank
699 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
700 }
701
702 // Get a map for folder ID to folder width
703 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
704 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
705 + " GROUP BY container;",
706 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
707
708 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800709 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
710 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800711 new Object[] {c.getLong(1) + 1, c.getLong(0)});
712 }
713
714 c.close();
715 db.setTransactionSuccessful();
716 } catch (SQLException ex) {
717 // Old version remains, which means we wipe old data
718 Log.e(TAG, ex.getMessage(), ex);
719 return false;
720 } finally {
721 db.endTransaction();
722 }
723 return true;
724 }
725
Kenny Guyed131872014-04-30 03:02:21 +0100726 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700727 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
728 // Default to the serial number of this user, for older
729 // shortcuts.
730 long userSerialNumber = userManager.getSerialNumberForUser(
731 UserHandleCompat.myUserHandle());
732 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
733 }
734
735 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100736 db.beginTransaction();
737 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700738 db.execSQL("ALTER TABLE favorites ADD COLUMN "
739 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100740 db.setTransactionSuccessful();
741 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100742 Log.e(TAG, ex.getMessage(), ex);
743 return false;
744 } finally {
745 db.endTransaction();
746 }
747 return true;
748 }
749
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700750 // Generates a new ID to use for an object in your database. This method should be only
751 // called from the main UI thread. As an exception, we do call it when we call the
752 // constructor from the worker thread; however, this doesn't extend until after the
753 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
754 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700755 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700756 public long generateNewItemId() {
757 if (mMaxItemId < 0) {
758 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700759 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 mMaxItemId += 1;
761 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700762 }
763
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700764 @Override
765 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
766 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
767 }
768
Winson Chungc763c4e2013-07-19 13:49:06 -0700769 public void updateMaxItemId(long id) {
770 mMaxItemId = id + 1;
771 }
772
Chris Wren5dee7af2013-12-20 17:22:11 -0500773 public void checkId(String table, ContentValues values) {
774 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
775 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
776 mMaxScreenId = Math.max(id, mMaxScreenId);
777 } else {
778 mMaxItemId = Math.max(id, mMaxItemId);
779 }
780 }
781
Adam Cohendcd297f2013-06-18 13:13:40 -0700782 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800783 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700784 }
785
786 // Generates a new ID to use for an workspace screen in your database. This method
787 // should be only called from the main UI thread. As an exception, we do call it when we
788 // call the constructor from the worker thread; however, this doesn't extend until after the
789 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
790 // after that point
791 public long generateNewScreenId() {
792 if (mMaxScreenId < 0) {
793 throw new RuntimeException("Error: max screen id was not initialized");
794 }
795 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800796 // Log to disk
797 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700798 return mMaxScreenId;
799 }
800
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800802 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800803 }
804
Adam Cohen091440a2015-03-18 14:16:05 -0700805 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700806 // 1. Ensure that externally added items have a valid item id
807 long id = generateNewItemId();
808 values.put(LauncherSettings.Favorites._ID, id);
809
810 // 2. In the case of an app widget, and if no app widget id is specified, we
811 // attempt allocate and bind the widget.
812 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
813 if (itemType != null &&
814 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
815 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
816
817 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
818 ComponentName cn = ComponentName.unflattenFromString(
819 values.getAsString(Favorites.APPWIDGET_PROVIDER));
820
821 if (cn != null) {
822 try {
823 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700824 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700825 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700826 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700827 }
828 } catch (RuntimeException e) {
829 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700830 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700831 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700832 } else {
833 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700834 }
835 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700836
837 // Add screen id if not present
838 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
839 if (!addScreenIdIfNecessary(screenId)) {
840 return false;
841 }
Adam Cohena043fa82014-07-23 14:49:38 -0700842 return true;
843 }
844
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700845 // Returns true of screen id exists, or if successfully added
846 private boolean addScreenIdIfNecessary(long screenId) {
847 if (!hasScreenId(screenId)) {
848 int rank = getMaxScreenRank() + 1;
849
850 ContentValues v = new ContentValues();
851 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
852 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
853 if (dbInsertAndCheck(this, getWritableDatabase(),
854 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
855 return false;
856 }
857 }
858 return true;
859 }
860
861 private boolean hasScreenId(long screenId) {
862 SQLiteDatabase db = getWritableDatabase();
863 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
864 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
865 if (c != null) {
866 int count = c.getCount();
867 c.close();
868 return count > 0;
869 } else {
870 return false;
871 }
872 }
873
874 private int getMaxScreenRank() {
875 SQLiteDatabase db = getWritableDatabase();
876 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
877 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
878
879 // get the result
880 final int maxRankIndex = 0;
881 int rank = -1;
882 if (c != null && c.moveToNext()) {
883 rank = c.getInt(maxRankIndex);
884 }
885 if (c != null) {
886 c.close();
887 }
888
889 return rank;
890 }
891
Adam Cohen091440a2015-03-18 14:16:05 -0700892 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700893 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700894 // TODO: Use multiple loaders with fall-back and transaction.
895 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700896
897 // Add the screens specified by the items above
898 Collections.sort(screenIds);
899 int rank = 0;
900 ContentValues values = new ContentValues();
901 for (Long id : screenIds) {
902 values.clear();
903 values.put(LauncherSettings.WorkspaceScreens._ID, id);
904 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
905 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
906 throw new RuntimeException("Failed initialize screen table"
907 + "from default layout");
908 }
909 rank++;
910 }
911
912 // Ensure that the max ids are initialized
913 mMaxItemId = initializeMaxItemId(db);
914 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700915
Adam Cohen71483f42014-05-15 14:04:01 -0700916 return count;
917 }
918
Adam Cohen091440a2015-03-18 14:16:05 -0700919 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500920 final ContentResolver resolver = mContext.getContentResolver();
921 Cursor c = null;
922 int count = 0;
923 int curScreen = 0;
924
925 try {
926 c = resolver.query(uri, null, null, null, "title ASC");
927 } catch (Exception e) {
928 // Ignore
929 }
930
Dan Sandlerd5024042014-01-09 15:01:33 -0500931 // We already have a favorites database in the old provider
932 if (c != null) {
933 try {
934 if (c.getCount() > 0) {
935 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
936 final int intentIndex
937 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
938 final int titleIndex
939 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
940 final int iconTypeIndex
941 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
942 final int iconIndex
943 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
944 final int iconPackageIndex
945 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
946 final int iconResourceIndex
947 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
948 final int containerIndex
949 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
950 final int itemTypeIndex
951 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
952 final int screenIndex
953 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
954 final int cellXIndex
955 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
956 final int cellYIndex
957 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
958 final int uriIndex
959 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
960 final int displayModeIndex
961 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100962 final int profileIndex
963 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500964
965 int i = 0;
966 int curX = 0;
967 int curY = 0;
968
969 final LauncherAppState app = LauncherAppState.getInstance();
970 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
971 final int width = (int) grid.numColumns;
972 final int height = (int) grid.numRows;
973 final int hotseatWidth = (int) grid.numHotseatIcons;
974
975 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
976
Adam Cohen72960972014-01-15 18:13:55 -0800977 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
978 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500979 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500980
981 while (c.moveToNext()) {
982 final int itemType = c.getInt(itemTypeIndex);
983 if (itemType != Favorites.ITEM_TYPE_APPLICATION
984 && itemType != Favorites.ITEM_TYPE_SHORTCUT
985 && itemType != Favorites.ITEM_TYPE_FOLDER) {
986 continue;
987 }
988
989 final int cellX = c.getInt(cellXIndex);
990 final int cellY = c.getInt(cellYIndex);
991 final int screen = c.getInt(screenIndex);
992 int container = c.getInt(containerIndex);
993 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100994
995 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
996 UserHandleCompat userHandle;
997 final long userSerialNumber;
998 if (profileIndex != -1 && !c.isNull(profileIndex)) {
999 userSerialNumber = c.getInt(profileIndex);
1000 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1001 } else {
1002 // Default to the serial number of this user, for older
1003 // shortcuts.
1004 userHandle = UserHandleCompat.myUserHandle();
1005 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1006 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001007
1008 if (userHandle == null) {
1009 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1010 continue;
1011 }
1012
Dan Sandlerd5024042014-01-09 15:01:33 -05001013 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001014 + c.getString(titleIndex) + "\" ("
1015 + cellX + "," + cellY + "@"
1016 + LauncherSettings.Favorites.containerToString(container)
1017 + "/" + screen
1018 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001019
1020 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001021
1022 final Intent intent;
1023 final ComponentName cn;
1024 try {
1025 intent = Intent.parseUri(intentStr, 0);
1026 } catch (URISyntaxException e) {
1027 // bogus intent?
1028 Launcher.addDumpLog(TAG,
1029 "skipping invalid intent uri", true);
1030 continue;
1031 }
1032
1033 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001034 if (TextUtils.isEmpty(intentStr)) {
1035 // no intent? no icon
1036 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1037 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001038 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001039 !LauncherModel.isValidPackageActivity(mContext, cn,
1040 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001041 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001042 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001043 "no longer exists.", true);
1044 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001045 } else if (container ==
1046 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1047 // Dedupe icons directly on the workspace
1048
Adam Cohen556f6132014-01-15 15:18:08 -08001049 // Canonicalize
1050 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001051 // does not, so we clear that out to keep them the same.
1052 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001053 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001054 int flags = intent.getFlags();
1055 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001056 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001057 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001058 if (seenIntents.contains(key)) {
1059 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001060 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001061 } else {
1062 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001063 }
1064 }
1065 }
1066
1067 ContentValues values = new ContentValues(c.getColumnCount());
1068 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1069 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1070 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1071 values.put(LauncherSettings.Favorites.ICON_TYPE,
1072 c.getInt(iconTypeIndex));
1073 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1074 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1075 c.getString(iconPackageIndex));
1076 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1077 c.getString(iconResourceIndex));
1078 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1079 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1080 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1081 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1082 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001083 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001084
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001085 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1086 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001087 }
1088
1089 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1090 // In a folder or in the hotseat, preserve position
1091 values.put(LauncherSettings.Favorites.SCREEN, screen);
1092 values.put(LauncherSettings.Favorites.CELLX, cellX);
1093 values.put(LauncherSettings.Favorites.CELLY, cellY);
1094 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001095 // For items contained directly on one of the workspace screen,
1096 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001097 }
1098
1099 values.put(LauncherSettings.Favorites.CONTAINER, container);
1100
Adam Cohen72960972014-01-15 18:13:55 -08001101 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1102 shortcuts.add(values);
1103 } else {
1104 folders.add(values);
1105 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001106 }
1107
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001108 // Now that we have all the hotseat icons, let's go through them left-right
1109 // and assign valid locations for them in the new hotseat
1110 final int N = hotseat.size();
1111 for (int idx=0; idx<N; idx++) {
1112 int hotseatX = hotseat.keyAt(idx);
1113 ContentValues values = hotseat.valueAt(idx);
1114
1115 if (hotseatX == grid.hotseatAllAppsRank) {
1116 // let's drop this in the next available hole in the hotseat
1117 while (++hotseatX < hotseatWidth) {
1118 if (hotseat.get(hotseatX) == null) {
1119 // found a spot! move it here
1120 values.put(LauncherSettings.Favorites.SCREEN,
1121 hotseatX);
1122 break;
1123 }
1124 }
1125 }
1126 if (hotseatX >= hotseatWidth) {
1127 // no room for you in the hotseat? it's off to the desktop with you
1128 values.put(LauncherSettings.Favorites.CONTAINER,
1129 Favorites.CONTAINER_DESKTOP);
1130 }
1131 }
1132
Adam Cohen72960972014-01-15 18:13:55 -08001133 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1134 // Folders first
1135 allItems.addAll(folders);
1136 // Then shortcuts
1137 allItems.addAll(shortcuts);
1138
1139 // Layout all the folders
1140 for (ContentValues values: allItems) {
1141 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1142 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1143 // Hotseat items and folder items have already had their
1144 // location information set. Nothing to be done here.
1145 continue;
1146 }
1147 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1148 values.put(LauncherSettings.Favorites.CELLX, curX);
1149 values.put(LauncherSettings.Favorites.CELLY, curY);
1150 curX = (curX + 1) % width;
1151 if (curX == 0) {
1152 curY = (curY + 1);
1153 }
1154 // Leave the last row of icons blank on every screen
1155 if (curY == height - 1) {
1156 curScreen = (int) generateNewScreenId();
1157 curY = 0;
1158 }
1159 }
1160
1161 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001162 db.beginTransaction();
1163 try {
Adam Cohen72960972014-01-15 18:13:55 -08001164 for (ContentValues row: allItems) {
1165 if (row == null) continue;
1166 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001167 < 0) {
1168 return;
1169 } else {
1170 count++;
1171 }
1172 }
1173 db.setTransactionSuccessful();
1174 } finally {
1175 db.endTransaction();
1176 }
1177 }
1178
1179 db.beginTransaction();
1180 try {
1181 for (i=0; i<=curScreen; i++) {
1182 final ContentValues values = new ContentValues();
1183 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1184 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1185 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1186 < 0) {
1187 return;
1188 }
1189 }
1190 db.setTransactionSuccessful();
1191 } finally {
1192 db.endTransaction();
1193 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001194
1195 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001196 }
1197 } finally {
1198 c.close();
1199 }
1200 }
1201
1202 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1203 + (curScreen+1) + " screens", true);
1204
1205 // ensure that new screens are created to hold these icons
1206 setFlagJustLoadedOldDb();
1207
1208 // Update max IDs; very important since we just grabbed IDs from another database
1209 mMaxItemId = initializeMaxItemId(db);
1210 mMaxScreenId = initializeMaxScreenId(db);
1211 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1212 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001213 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001214
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001215 /**
1216 * @return the max _id in the provided table.
1217 */
Adam Cohen091440a2015-03-18 14:16:05 -07001218 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001219 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1220 // get the result
1221 long id = -1;
1222 if (c != null && c.moveToNext()) {
1223 id = c.getLong(0);
1224 }
1225 if (c != null) {
1226 c.close();
1227 }
1228
1229 if (id == -1) {
1230 throw new RuntimeException("Error: could not query max id in " + table);
1231 }
1232
1233 return id;
1234 }
1235
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001236 static class SqlArguments {
1237 public final String table;
1238 public final String where;
1239 public final String[] args;
1240
1241 SqlArguments(Uri url, String where, String[] args) {
1242 if (url.getPathSegments().size() == 1) {
1243 this.table = url.getPathSegments().get(0);
1244 this.where = where;
1245 this.args = args;
1246 } else if (url.getPathSegments().size() != 2) {
1247 throw new IllegalArgumentException("Invalid URI: " + url);
1248 } else if (!TextUtils.isEmpty(where)) {
1249 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1250 } else {
1251 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001252 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001253 this.args = null;
1254 }
1255 }
1256
1257 SqlArguments(Uri url) {
1258 if (url.getPathSegments().size() == 1) {
1259 table = url.getPathSegments().get(0);
1260 where = null;
1261 args = null;
1262 } else {
1263 throw new IllegalArgumentException("Invalid URI: " + url);
1264 }
1265 }
1266 }
Adam Cohen72960972014-01-15 18:13:55 -08001267}