blob: dfacfa3e445aff44964f603ee88166018f786f01 [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";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080074 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Adam Cohena043fa82014-07-23 14:49:38 -070076 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
77
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Anjali Koppal67e7cae2014-03-13 12:14:12 -070080 private LauncherProviderChangeListener mListener;
81
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070082 /**
Romain Guy73b979d2009-06-09 12:57:21 -070083 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070084 * {@link AppWidgetHost#deleteHost()} is called during database creation.
85 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
86 */
87 static final Uri CONTENT_APPWIDGET_RESET_URI =
88 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070089
Michael Jurkaa8c760d2011-04-28 14:59:33 -070090 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
92 @Override
93 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040094 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080095 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040096 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080097 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040098 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099 return true;
100 }
101
Winson Chung0b560dd2014-01-21 13:00:26 -0800102 public boolean wasNewDbCreated() {
103 return mOpenHelper.wasNewDbCreated();
104 }
105
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700106 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
107 mListener = listener;
108 }
109
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110 @Override
111 public String getType(Uri uri) {
112 SqlArguments args = new SqlArguments(uri, null, null);
113 if (TextUtils.isEmpty(args.where)) {
114 return "vnd.android.cursor.dir/" + args.table;
115 } else {
116 return "vnd.android.cursor.item/" + args.table;
117 }
118 }
119
120 @Override
121 public Cursor query(Uri uri, String[] projection, String selection,
122 String[] selectionArgs, String sortOrder) {
123
124 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
125 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
126 qb.setTables(args.table);
127
Romain Guy73b979d2009-06-09 12:57:21 -0700128 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800129 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
130 result.setNotificationUri(getContext().getContentResolver(), uri);
131
132 return result;
133 }
134
Adam Cohen091440a2015-03-18 14:16:05 -0700135 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700136 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500137 if (values == null) {
138 throw new RuntimeException("Error: attempting to insert null values");
139 }
Adam Cohen71483f42014-05-15 14:04:01 -0700140 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 throw new RuntimeException("Error: attempting to add item without specifying an id");
142 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500143 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700144 return db.insert(table, nullColumnHack, values);
145 }
146
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800147 @Override
148 public Uri insert(Uri uri, ContentValues initialValues) {
149 SqlArguments args = new SqlArguments(uri);
150
Adam Cohena043fa82014-07-23 14:49:38 -0700151 // In very limited cases, we support system|signature permission apps to add to the db
152 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
153 if (externalAdd != null && "true".equals(externalAdd)) {
154 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);
165 sendNotify(uri);
166
167 return uri;
168 }
169
Adam Cohena043fa82014-07-23 14:49:38 -0700170
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171 @Override
172 public int bulkInsert(Uri uri, ContentValues[] values) {
173 SqlArguments args = new SqlArguments(uri);
174
175 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
176 db.beginTransaction();
177 try {
178 int numValues = values.length;
179 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400180 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
182 return 0;
183 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 }
185 db.setTransactionSuccessful();
186 } finally {
187 db.endTransaction();
188 }
189
190 sendNotify(uri);
191 return values.length;
192 }
193
194 @Override
Yura085c8532014-02-11 15:15:29 +0000195 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
196 throws OperationApplicationException {
197 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
198 db.beginTransaction();
199 try {
200 ContentProviderResult[] result = super.applyBatch(operations);
201 db.setTransactionSuccessful();
202 return result;
203 } finally {
204 db.endTransaction();
205 }
206 }
207
208 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 public int delete(Uri uri, String selection, String[] selectionArgs) {
210 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
211
212 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
213 int count = db.delete(args.table, args.where, args.args);
214 if (count > 0) sendNotify(uri);
215
216 return count;
217 }
218
219 @Override
220 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
221 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
222
Chris Wren1ada10d2013-09-13 18:01:38 -0400223 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
225 int count = db.update(args.table, values, args.where, args.args);
226 if (count > 0) sendNotify(uri);
227
228 return count;
229 }
230
231 private void sendNotify(Uri uri) {
232 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
233 if (notify == null || "true".equals(notify)) {
234 getContext().getContentResolver().notifyChange(uri, null);
235 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400236
237 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400238 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700239 if (mListener != null) {
240 mListener.onLauncherProviderChange();
241 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400242 }
243
Adam Cohen091440a2015-03-18 14:16:05 -0700244 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400245 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 }
247
Adam Cohendcd297f2013-06-18 13:13:40 -0700248 public long generateNewItemId() {
249 return mOpenHelper.generateNewItemId();
250 }
251
Winson Chungc763c4e2013-07-19 13:49:06 -0700252 public void updateMaxItemId(long id) {
253 mOpenHelper.updateMaxItemId(id);
254 }
255
Adam Cohendcd297f2013-06-18 13:13:40 -0700256 public long generateNewScreenId() {
257 return mOpenHelper.generateNewScreenId();
258 }
259
Brian Muramatsu5524b492012-10-02 16:55:54 -0700260 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700261 * Clears all the data for a fresh start.
262 */
263 synchronized public void createEmptyDB() {
264 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
265 }
266
Sunny Goyal33d44382014-10-16 09:24:19 -0700267 public void clearFlagEmptyDbCreated() {
268 String spKey = LauncherAppState.getSharedPreferencesKey();
269 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
270 .edit()
271 .remove(EMPTY_DATABASE_CREATED)
272 .commit();
273 }
274
Sunny Goyal42de82f2014-09-26 22:09:29 -0700275 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700276 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700277 * 1) From the app restrictions
278 * 2) From a package provided by play store
279 * 3) From a partner configuration APK, already in the system image
280 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700281 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700282 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400283 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700284 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700285
Winson Chungc763c4e2013-07-19 13:49:06 -0700286 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500287 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200288
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700289 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
290 if (loader == null) {
291 loader = AutoInstallsLayout.get(getContext(),
292 mOpenHelper.mAppWidgetHost, mOpenHelper);
293 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700294 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700295 final Partner partner = Partner.get(getContext().getPackageManager());
296 if (partner != null && partner.hasDefaultLayout()) {
297 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700298 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700299 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700300 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700301 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
302 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700303 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700304 }
305 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700306
Sunny Goyal9d219682014-10-23 14:21:02 -0700307 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700308 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700309 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700310 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800311
312 // There might be some partially restored DB items, due to buggy restore logic in
313 // previous versions of launcher.
314 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700315 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700316 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
317 && usingExternallyProvidedLayout) {
318 // Unable to load external layout. Cleanup and load the internal layout.
319 createEmptyDB();
320 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
321 getDefaultLayoutParser());
322 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700323 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700324 }
325 }
326
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700327 /**
328 * Creates workspace loader from an XML resource listed in the app restrictions.
329 *
330 * @return the loader if the restrictions are set and the resource exists; null otherwise.
331 */
332 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
333 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
334 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
335 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
336 return null;
337 }
338
339 Context ctx = getContext();
340 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
341 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
342 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
343
344 if (packageName != null) {
345 try {
346 Resources targetResources = ctx.getPackageManager()
347 .getResourcesForApplication(packageName);
348 return AutoInstallsLayout.get(ctx, packageName, targetResources,
349 mOpenHelper.mAppWidgetHost, mOpenHelper);
350 } catch (NameNotFoundException e) {
351 Log.e(TAG, "Target package for restricted profile not found", e);
352 return null;
353 }
354 }
355 return null;
356 }
357
Sunny Goyal9d219682014-10-23 14:21:02 -0700358 private DefaultLayoutParser getDefaultLayoutParser() {
359 int defaultLayout = LauncherAppState.getInstance()
360 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
361 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
362 mOpenHelper, getContext().getResources(), defaultLayout);
363 }
364
Dan Sandlerd5024042014-01-09 15:01:33 -0500365 public void migrateLauncher2Shortcuts() {
366 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400367 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500368 }
369
Sunny Goyal08f72612015-01-05 13:41:43 -0800370 public void updateFolderItemsRank() {
371 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
372 }
373
Dan Sandlerd5024042014-01-09 15:01:33 -0500374 public void deleteDatabase() {
375 // Are you sure? (y/n)
376 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500377 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500378 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500379 if (dbFile.exists()) {
380 SQLiteDatabase.deleteDatabase(dbFile);
381 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500382 mOpenHelper = new DatabaseHelper(getContext());
383 }
384
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700385 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800386 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700387 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700388 private long mMaxItemId = -1;
389 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800390
Winson Chung0b560dd2014-01-21 13:00:26 -0800391 private boolean mNewDbCreated = false;
392
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800393 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100394 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800395 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700396 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700397
398 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
399 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700400 if (mMaxItemId == -1) {
401 mMaxItemId = initializeMaxItemId(getWritableDatabase());
402 }
403 if (mMaxScreenId == -1) {
404 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700405 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800406 }
407
Winson Chung0b560dd2014-01-21 13:00:26 -0800408 public boolean wasNewDbCreated() {
409 return mNewDbCreated;
410 }
411
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700412 /**
413 * Send notification that we've deleted the {@link AppWidgetHost},
414 * probably as part of the initial database creation. The receiver may
415 * want to re-call {@link AppWidgetHost#startListening()} to ensure
416 * callbacks are correctly set.
417 */
418 private void sendAppWidgetResetNotify() {
419 final ContentResolver resolver = mContext.getContentResolver();
420 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
421 }
422
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800423 @Override
424 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800425 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700426
Adam Cohendcd297f2013-06-18 13:13:40 -0700427 mMaxItemId = 1;
428 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800429 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700430
Kenny Guyed131872014-04-30 03:02:21 +0100431 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
432 long userSerialNumber = userManager.getSerialNumberForUser(
433 UserHandleCompat.myUserHandle());
434
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800435 db.execSQL("CREATE TABLE favorites (" +
436 "_id INTEGER PRIMARY KEY," +
437 "title TEXT," +
438 "intent TEXT," +
439 "container INTEGER," +
440 "screen INTEGER," +
441 "cellX INTEGER," +
442 "cellY INTEGER," +
443 "spanX INTEGER," +
444 "spanY INTEGER," +
445 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700446 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800447 "isShortcut INTEGER," +
448 "iconType INTEGER," +
449 "iconPackage TEXT," +
450 "iconResource TEXT," +
451 "icon BLOB," +
452 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400453 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400454 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500455 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100456 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800457 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700458 "rank INTEGER NOT NULL DEFAULT 0," +
459 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800460 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700461 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800462
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700463 // Database was just created, so wipe any previous widgets
464 if (mAppWidgetHost != null) {
465 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700466 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800467 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700468
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800469 // Fresh and clean launcher DB.
470 mMaxItemId = initializeMaxItemId(db);
471 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 }
473
Adam Cohendcd297f2013-06-18 13:13:40 -0700474 private void addWorkspacesTable(SQLiteDatabase db) {
475 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800476 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400477 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
478 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700479 ");");
480 }
481
Adam Cohen119285e2014-04-02 16:59:08 -0700482 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700483 // Delete items directly on the workspace who's screen id doesn't exist
484 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
485 // AND container = -100"
486 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
487 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700488 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700489 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
490 " AND " +
491 LauncherSettings.Favorites.CONTAINER + " = " +
492 LauncherSettings.Favorites.CONTAINER_DESKTOP;
493 db.execSQL(removeOrphanedDesktopItems);
494
495 // Delete items contained in folders which no longer exist (after above statement)
496 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
497 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
498 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
499 " WHERE " +
500 LauncherSettings.Favorites.CONTAINER + " <> " +
501 LauncherSettings.Favorites.CONTAINER_DESKTOP +
502 " AND "
503 + LauncherSettings.Favorites.CONTAINER + " <> " +
504 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
505 " AND "
506 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
507 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
508 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
509 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
510 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700511 }
512
Winson Chungc763c4e2013-07-19 13:49:06 -0700513 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400514 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700515 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800516 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700517 }
518
Winson Chungc763c4e2013-07-19 13:49:06 -0700519 private void setFlagEmptyDbCreated() {
520 String spKey = LauncherAppState.getSharedPreferencesKey();
521 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800522 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700523 }
524
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800525 @Override
526 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700527 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800528 switch (oldVersion) {
529 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800530 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800531 case 12: {
532 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
533 // to persist workspace screens and their relative order.
534 mMaxScreenId = 0;
535 addWorkspacesTable(db);
536 }
537 case 13: {
538 db.beginTransaction();
539 try {
540 // Insert new column for holding widget provider name
541 db.execSQL("ALTER TABLE favorites " +
542 "ADD COLUMN appWidgetProvider TEXT;");
543 db.setTransactionSuccessful();
544 } catch (SQLException ex) {
545 Log.e(TAG, ex.getMessage(), ex);
546 // Old version remains, which means we wipe old data
547 break;
548 } finally {
549 db.endTransaction();
550 }
551 }
552 case 14: {
553 db.beginTransaction();
554 try {
555 // Insert new column for holding update timestamp
556 db.execSQL("ALTER TABLE favorites " +
557 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
558 db.execSQL("ALTER TABLE workspaceScreens " +
559 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
560 db.setTransactionSuccessful();
561 } catch (SQLException ex) {
562 Log.e(TAG, ex.getMessage(), ex);
563 // Old version remains, which means we wipe old data
564 break;
565 } finally {
566 db.endTransaction();
567 }
568 }
569 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700570 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800571 // Old version remains, which means we wipe old data
572 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800573 }
574 }
575 case 16: {
576 // We use the db version upgrade here to identify users who may not have seen
577 // clings yet (because they weren't available), but for whom the clings are now
578 // available (tablet users). Because one of the possible cling flows (migration)
579 // is very destructive (wipes out workspaces), we want to prevent this from showing
580 // until clear data. We do so by marking that the clings have been shown.
581 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
582 }
583 case 17: {
584 // No-op
585 }
586 case 18: {
587 // Due to a data loss bug, some users may have items associated with screen ids
588 // which no longer exist. Since this can cause other problems, and since the user
589 // will never see these items anyway, we use database upgrade as an opportunity to
590 // clean things up.
591 removeOrphanedItems(db);
592 }
593 case 19: {
594 // Add userId column
595 if (!addProfileColumn(db)) {
596 // Old version remains, which means we wipe old data
597 break;
598 }
599 }
600 case 20:
601 if (!updateFolderItemsRank(db, true)) {
602 break;
603 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800604 case 21:
605 // Recreate workspace table with screen id a primary key
606 if (!recreateWorkspaceTable(db)) {
607 break;
608 }
609 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700610 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
611 // Old version remains, which means we wipe old data
612 break;
613 }
614 }
615 case 23: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800616 // DB Upgraded successfully
617 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400618 }
619 }
620
Sunny Goyala2cc6242015-01-14 14:23:02 -0800621 // DB was not upgraded
622 Log.w(TAG, "Destroying all old data.");
623 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800625
Adam Cohen9b1d0622014-05-21 19:01:57 -0700626 @Override
627 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
628 // This shouldn't happen -- throw our hands up in the air and start over.
629 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
630 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700631 createEmptyDB(db);
632 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700633
Sunny Goyal42de82f2014-09-26 22:09:29 -0700634
635 /**
636 * Clears all the data for a fresh start.
637 */
638 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700639 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
640 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
641 onCreate(db);
642 }
643
Sunny Goyald2f38192015-02-25 10:46:34 -0800644 /**
645 * Recreates workspace table and migrates data to the new table.
646 */
647 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
648 db.beginTransaction();
649 try {
650 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
651 new String[] {LauncherSettings.WorkspaceScreens._ID},
652 null, null, null, null,
653 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
654 ArrayList<Long> sortedIDs = new ArrayList<Long>();
655 long maxId = 0;
656 try {
657 while (c.moveToNext()) {
658 Long id = c.getLong(0);
659 if (!sortedIDs.contains(id)) {
660 sortedIDs.add(id);
661 maxId = Math.max(maxId, id);
662 }
663 }
664 } finally {
665 c.close();
666 }
667
668 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
669 addWorkspacesTable(db);
670
671 // Add all screen ids back
672 int total = sortedIDs.size();
673 for (int i = 0; i < total; i++) {
674 ContentValues values = new ContentValues();
675 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
676 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
677 addModifiedTime(values);
678 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
679 }
680 db.setTransactionSuccessful();
681 mMaxScreenId = maxId;
682 } catch (SQLException ex) {
683 // Old version remains, which means we wipe old data
684 Log.e(TAG, ex.getMessage(), ex);
685 return false;
686 } finally {
687 db.endTransaction();
688 }
689 return true;
690 }
691
Adam Cohen091440a2015-03-18 14:16:05 -0700692 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800693 db.beginTransaction();
694 try {
695 if (addRankColumn) {
696 // Insert new column for holding rank
697 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
698 }
699
700 // Get a map for folder ID to folder width
701 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
702 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
703 + " GROUP BY container;",
704 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
705
706 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800707 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
708 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800709 new Object[] {c.getLong(1) + 1, c.getLong(0)});
710 }
711
712 c.close();
713 db.setTransactionSuccessful();
714 } catch (SQLException ex) {
715 // Old version remains, which means we wipe old data
716 Log.e(TAG, ex.getMessage(), ex);
717 return false;
718 } finally {
719 db.endTransaction();
720 }
721 return true;
722 }
723
Kenny Guyed131872014-04-30 03:02:21 +0100724 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700725 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
726 // Default to the serial number of this user, for older
727 // shortcuts.
728 long userSerialNumber = userManager.getSerialNumberForUser(
729 UserHandleCompat.myUserHandle());
730 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
731 }
732
733 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100734 db.beginTransaction();
735 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700736 db.execSQL("ALTER TABLE favorites ADD COLUMN "
737 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100738 db.setTransactionSuccessful();
739 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100740 Log.e(TAG, ex.getMessage(), ex);
741 return false;
742 } finally {
743 db.endTransaction();
744 }
745 return true;
746 }
747
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700748 // Generates a new ID to use for an object in your database. This method should be only
749 // called from the main UI thread. As an exception, we do call it when we call the
750 // constructor from the worker thread; however, this doesn't extend until after the
751 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
752 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700753 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700754 public long generateNewItemId() {
755 if (mMaxItemId < 0) {
756 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700757 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 mMaxItemId += 1;
759 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700760 }
761
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700762 @Override
763 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
764 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
765 }
766
Winson Chungc763c4e2013-07-19 13:49:06 -0700767 public void updateMaxItemId(long id) {
768 mMaxItemId = id + 1;
769 }
770
Chris Wren5dee7af2013-12-20 17:22:11 -0500771 public void checkId(String table, ContentValues values) {
772 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
773 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
774 mMaxScreenId = Math.max(id, mMaxScreenId);
775 } else {
776 mMaxItemId = Math.max(id, mMaxItemId);
777 }
778 }
779
Adam Cohendcd297f2013-06-18 13:13:40 -0700780 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800781 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700782 }
783
784 // Generates a new ID to use for an workspace screen in your database. This method
785 // should be only called from the main UI thread. As an exception, we do call it when we
786 // call the constructor from the worker thread; however, this doesn't extend until after the
787 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
788 // after that point
789 public long generateNewScreenId() {
790 if (mMaxScreenId < 0) {
791 throw new RuntimeException("Error: max screen id was not initialized");
792 }
793 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800794 // Log to disk
795 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700796 return mMaxScreenId;
797 }
798
Adam Cohendcd297f2013-06-18 13:13:40 -0700799 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800800 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800801 }
802
Adam Cohen091440a2015-03-18 14:16:05 -0700803 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700804 // 1. Ensure that externally added items have a valid item id
805 long id = generateNewItemId();
806 values.put(LauncherSettings.Favorites._ID, id);
807
808 // 2. In the case of an app widget, and if no app widget id is specified, we
809 // attempt allocate and bind the widget.
810 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
811 if (itemType != null &&
812 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
813 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
814
815 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
816 ComponentName cn = ComponentName.unflattenFromString(
817 values.getAsString(Favorites.APPWIDGET_PROVIDER));
818
819 if (cn != null) {
820 try {
821 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700822 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700823 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700824 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700825 }
826 } catch (RuntimeException e) {
827 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700828 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700829 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700830 } else {
831 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700832 }
833 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700834
835 // Add screen id if not present
836 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
837 if (!addScreenIdIfNecessary(screenId)) {
838 return false;
839 }
Adam Cohena043fa82014-07-23 14:49:38 -0700840 return true;
841 }
842
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700843 // Returns true of screen id exists, or if successfully added
844 private boolean addScreenIdIfNecessary(long screenId) {
845 if (!hasScreenId(screenId)) {
846 int rank = getMaxScreenRank() + 1;
847
848 ContentValues v = new ContentValues();
849 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
850 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
851 if (dbInsertAndCheck(this, getWritableDatabase(),
852 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
853 return false;
854 }
855 }
856 return true;
857 }
858
859 private boolean hasScreenId(long screenId) {
860 SQLiteDatabase db = getWritableDatabase();
861 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
862 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
863 if (c != null) {
864 int count = c.getCount();
865 c.close();
866 return count > 0;
867 } else {
868 return false;
869 }
870 }
871
872 private int getMaxScreenRank() {
873 SQLiteDatabase db = getWritableDatabase();
874 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
875 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
876
877 // get the result
878 final int maxRankIndex = 0;
879 int rank = -1;
880 if (c != null && c.moveToNext()) {
881 rank = c.getInt(maxRankIndex);
882 }
883 if (c != null) {
884 c.close();
885 }
886
887 return rank;
888 }
889
Adam Cohen091440a2015-03-18 14:16:05 -0700890 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700891 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700892 // TODO: Use multiple loaders with fall-back and transaction.
893 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700894
895 // Add the screens specified by the items above
896 Collections.sort(screenIds);
897 int rank = 0;
898 ContentValues values = new ContentValues();
899 for (Long id : screenIds) {
900 values.clear();
901 values.put(LauncherSettings.WorkspaceScreens._ID, id);
902 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
903 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
904 throw new RuntimeException("Failed initialize screen table"
905 + "from default layout");
906 }
907 rank++;
908 }
909
910 // Ensure that the max ids are initialized
911 mMaxItemId = initializeMaxItemId(db);
912 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700913
Adam Cohen71483f42014-05-15 14:04:01 -0700914 return count;
915 }
916
Adam Cohen091440a2015-03-18 14:16:05 -0700917 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500918 final ContentResolver resolver = mContext.getContentResolver();
919 Cursor c = null;
920 int count = 0;
921 int curScreen = 0;
922
923 try {
924 c = resolver.query(uri, null, null, null, "title ASC");
925 } catch (Exception e) {
926 // Ignore
927 }
928
Dan Sandlerd5024042014-01-09 15:01:33 -0500929 // We already have a favorites database in the old provider
930 if (c != null) {
931 try {
932 if (c.getCount() > 0) {
933 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
934 final int intentIndex
935 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
936 final int titleIndex
937 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
938 final int iconTypeIndex
939 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
940 final int iconIndex
941 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
942 final int iconPackageIndex
943 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
944 final int iconResourceIndex
945 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
946 final int containerIndex
947 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
948 final int itemTypeIndex
949 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
950 final int screenIndex
951 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
952 final int cellXIndex
953 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
954 final int cellYIndex
955 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
956 final int uriIndex
957 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
958 final int displayModeIndex
959 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100960 final int profileIndex
961 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500962
963 int i = 0;
964 int curX = 0;
965 int curY = 0;
966
967 final LauncherAppState app = LauncherAppState.getInstance();
968 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
969 final int width = (int) grid.numColumns;
970 final int height = (int) grid.numRows;
971 final int hotseatWidth = (int) grid.numHotseatIcons;
972
973 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
974
Adam Cohen72960972014-01-15 18:13:55 -0800975 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
976 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500977 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500978
979 while (c.moveToNext()) {
980 final int itemType = c.getInt(itemTypeIndex);
981 if (itemType != Favorites.ITEM_TYPE_APPLICATION
982 && itemType != Favorites.ITEM_TYPE_SHORTCUT
983 && itemType != Favorites.ITEM_TYPE_FOLDER) {
984 continue;
985 }
986
987 final int cellX = c.getInt(cellXIndex);
988 final int cellY = c.getInt(cellYIndex);
989 final int screen = c.getInt(screenIndex);
990 int container = c.getInt(containerIndex);
991 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100992
993 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
994 UserHandleCompat userHandle;
995 final long userSerialNumber;
996 if (profileIndex != -1 && !c.isNull(profileIndex)) {
997 userSerialNumber = c.getInt(profileIndex);
998 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
999 } else {
1000 // Default to the serial number of this user, for older
1001 // shortcuts.
1002 userHandle = UserHandleCompat.myUserHandle();
1003 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1004 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001005
1006 if (userHandle == null) {
1007 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1008 continue;
1009 }
1010
Dan Sandlerd5024042014-01-09 15:01:33 -05001011 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001012 + c.getString(titleIndex) + "\" ("
1013 + cellX + "," + cellY + "@"
1014 + LauncherSettings.Favorites.containerToString(container)
1015 + "/" + screen
1016 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001017
1018 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001019
1020 final Intent intent;
1021 final ComponentName cn;
1022 try {
1023 intent = Intent.parseUri(intentStr, 0);
1024 } catch (URISyntaxException e) {
1025 // bogus intent?
1026 Launcher.addDumpLog(TAG,
1027 "skipping invalid intent uri", true);
1028 continue;
1029 }
1030
1031 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001032 if (TextUtils.isEmpty(intentStr)) {
1033 // no intent? no icon
1034 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1035 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001036 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001037 !LauncherModel.isValidPackageActivity(mContext, cn,
1038 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001039 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001040 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001041 "no longer exists.", true);
1042 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001043 } else if (container ==
1044 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1045 // Dedupe icons directly on the workspace
1046
Adam Cohen556f6132014-01-15 15:18:08 -08001047 // Canonicalize
1048 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001049 // does not, so we clear that out to keep them the same.
1050 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001051 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001052 int flags = intent.getFlags();
1053 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001054 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001055 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001056 if (seenIntents.contains(key)) {
1057 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001058 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001059 } else {
1060 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001061 }
1062 }
1063 }
1064
1065 ContentValues values = new ContentValues(c.getColumnCount());
1066 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1067 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1068 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1069 values.put(LauncherSettings.Favorites.ICON_TYPE,
1070 c.getInt(iconTypeIndex));
1071 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1072 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1073 c.getString(iconPackageIndex));
1074 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1075 c.getString(iconResourceIndex));
1076 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1077 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1078 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1079 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1080 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001081 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001082
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001083 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1084 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001085 }
1086
1087 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1088 // In a folder or in the hotseat, preserve position
1089 values.put(LauncherSettings.Favorites.SCREEN, screen);
1090 values.put(LauncherSettings.Favorites.CELLX, cellX);
1091 values.put(LauncherSettings.Favorites.CELLY, cellY);
1092 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001093 // For items contained directly on one of the workspace screen,
1094 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001095 }
1096
1097 values.put(LauncherSettings.Favorites.CONTAINER, container);
1098
Adam Cohen72960972014-01-15 18:13:55 -08001099 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1100 shortcuts.add(values);
1101 } else {
1102 folders.add(values);
1103 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001104 }
1105
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001106 // Now that we have all the hotseat icons, let's go through them left-right
1107 // and assign valid locations for them in the new hotseat
1108 final int N = hotseat.size();
1109 for (int idx=0; idx<N; idx++) {
1110 int hotseatX = hotseat.keyAt(idx);
1111 ContentValues values = hotseat.valueAt(idx);
1112
1113 if (hotseatX == grid.hotseatAllAppsRank) {
1114 // let's drop this in the next available hole in the hotseat
1115 while (++hotseatX < hotseatWidth) {
1116 if (hotseat.get(hotseatX) == null) {
1117 // found a spot! move it here
1118 values.put(LauncherSettings.Favorites.SCREEN,
1119 hotseatX);
1120 break;
1121 }
1122 }
1123 }
1124 if (hotseatX >= hotseatWidth) {
1125 // no room for you in the hotseat? it's off to the desktop with you
1126 values.put(LauncherSettings.Favorites.CONTAINER,
1127 Favorites.CONTAINER_DESKTOP);
1128 }
1129 }
1130
Adam Cohen72960972014-01-15 18:13:55 -08001131 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1132 // Folders first
1133 allItems.addAll(folders);
1134 // Then shortcuts
1135 allItems.addAll(shortcuts);
1136
1137 // Layout all the folders
1138 for (ContentValues values: allItems) {
1139 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1140 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1141 // Hotseat items and folder items have already had their
1142 // location information set. Nothing to be done here.
1143 continue;
1144 }
1145 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1146 values.put(LauncherSettings.Favorites.CELLX, curX);
1147 values.put(LauncherSettings.Favorites.CELLY, curY);
1148 curX = (curX + 1) % width;
1149 if (curX == 0) {
1150 curY = (curY + 1);
1151 }
1152 // Leave the last row of icons blank on every screen
1153 if (curY == height - 1) {
1154 curScreen = (int) generateNewScreenId();
1155 curY = 0;
1156 }
1157 }
1158
1159 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001160 db.beginTransaction();
1161 try {
Adam Cohen72960972014-01-15 18:13:55 -08001162 for (ContentValues row: allItems) {
1163 if (row == null) continue;
1164 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001165 < 0) {
1166 return;
1167 } else {
1168 count++;
1169 }
1170 }
1171 db.setTransactionSuccessful();
1172 } finally {
1173 db.endTransaction();
1174 }
1175 }
1176
1177 db.beginTransaction();
1178 try {
1179 for (i=0; i<=curScreen; i++) {
1180 final ContentValues values = new ContentValues();
1181 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1182 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1183 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1184 < 0) {
1185 return;
1186 }
1187 }
1188 db.setTransactionSuccessful();
1189 } finally {
1190 db.endTransaction();
1191 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001192
1193 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001194 }
1195 } finally {
1196 c.close();
1197 }
1198 }
1199
1200 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1201 + (curScreen+1) + " screens", true);
1202
1203 // ensure that new screens are created to hold these icons
1204 setFlagJustLoadedOldDb();
1205
1206 // Update max IDs; very important since we just grabbed IDs from another database
1207 mMaxItemId = initializeMaxItemId(db);
1208 mMaxScreenId = initializeMaxScreenId(db);
1209 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1210 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001211 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001212
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001213 /**
1214 * @return the max _id in the provided table.
1215 */
Adam Cohen091440a2015-03-18 14:16:05 -07001216 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001217 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1218 // get the result
1219 long id = -1;
1220 if (c != null && c.moveToNext()) {
1221 id = c.getLong(0);
1222 }
1223 if (c != null) {
1224 c.close();
1225 }
1226
1227 if (id == -1) {
1228 throw new RuntimeException("Error: could not query max id in " + table);
1229 }
1230
1231 return id;
1232 }
1233
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001234 static class SqlArguments {
1235 public final String table;
1236 public final String where;
1237 public final String[] args;
1238
1239 SqlArguments(Uri url, String where, String[] args) {
1240 if (url.getPathSegments().size() == 1) {
1241 this.table = url.getPathSegments().get(0);
1242 this.where = where;
1243 this.args = args;
1244 } else if (url.getPathSegments().size() != 2) {
1245 throw new IllegalArgumentException("Invalid URI: " + url);
1246 } else if (!TextUtils.isEmpty(where)) {
1247 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1248 } else {
1249 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001250 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001251 this.args = null;
1252 }
1253 }
1254
1255 SqlArguments(Uri url) {
1256 if (url.getPathSegments().size() == 1) {
1257 table = url.getPathSegments().get(0);
1258 where = null;
1259 args = null;
1260 } else {
1261 throw new IllegalArgumentException("Invalid URI: " + url);
1262 }
1263 }
1264 }
Adam Cohen72960972014-01-15 18:13:55 -08001265}