blob: 6dd1305052fbcd71a930e500d538c1c85b8c5725 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
The Android Open Source Project7376fae2009-03-11 12:11:58 -070019import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070020import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080021import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070022import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000023import android.content.ContentProviderOperation;
24import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.database.Cursor;
34import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070035import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.net.Uri;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080039import android.os.StrictMode;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050042import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070043
Sunny Goyal0fe505b2014-08-06 09:55:36 -070044import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
45import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010046import com.android.launcher3.compat.UserHandleCompat;
47import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040048import com.android.launcher3.config.ProviderConfig;
Adam Cohen091440a2015-03-18 14:16:05 -070049import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070050
Dan Sandlerd5024042014-01-09 15:01:33 -050051import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070052import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070053import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070054import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050055import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056
The Android Open Source Project31dd5032009-03-03 19:32:27 -080057public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080058 private static final String TAG = "Launcher.LauncherProvider";
59 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080060
Sunny Goyal5d85c442015-03-10 13:14:47 -070061 private static final int DATABASE_VERSION = 23;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062
Adam Cohene25af792013-06-06 23:08:25 -070063 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040064 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066 static final String TABLE_FAVORITES = "favorites";
Adam Cohendcd297f2013-06-18 13:13:40 -070067 static final String TABLE_WORKSPACE_SCREENS = "workspaceScreens";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068 static final String PARAMETER_NOTIFY = "notify";
Sunny Goyale87e6ab2014-11-21 22:42:53 -080069 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Adam Cohena043fa82014-07-23 14:49:38 -070071 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
72
Anjali Koppal67e7cae2014-03-13 12:14:12 -070073 private LauncherProviderChangeListener mListener;
74
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070075 /**
Romain Guy73b979d2009-06-09 12:57:21 -070076 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070077 * {@link AppWidgetHost#deleteHost()} is called during database creation.
78 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
79 */
80 static final Uri CONTENT_APPWIDGET_RESET_URI =
81 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070082
Michael Jurkaa8c760d2011-04-28 14:59:33 -070083 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
85 @Override
86 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040087 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080088 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040089 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080090 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040091 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 return true;
93 }
94
Winson Chung0b560dd2014-01-21 13:00:26 -080095 public boolean wasNewDbCreated() {
96 return mOpenHelper.wasNewDbCreated();
97 }
98
Anjali Koppal67e7cae2014-03-13 12:14:12 -070099 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
100 mListener = listener;
101 }
102
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103 @Override
104 public String getType(Uri uri) {
105 SqlArguments args = new SqlArguments(uri, null, null);
106 if (TextUtils.isEmpty(args.where)) {
107 return "vnd.android.cursor.dir/" + args.table;
108 } else {
109 return "vnd.android.cursor.item/" + args.table;
110 }
111 }
112
113 @Override
114 public Cursor query(Uri uri, String[] projection, String selection,
115 String[] selectionArgs, String sortOrder) {
116
117 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
118 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
119 qb.setTables(args.table);
120
Romain Guy73b979d2009-06-09 12:57:21 -0700121 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
123 result.setNotificationUri(getContext().getContentResolver(), uri);
124
125 return result;
126 }
127
Adam Cohen091440a2015-03-18 14:16:05 -0700128 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500130 if (values == null) {
131 throw new RuntimeException("Error: attempting to insert null values");
132 }
Adam Cohen71483f42014-05-15 14:04:01 -0700133 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134 throw new RuntimeException("Error: attempting to add item without specifying an id");
135 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500136 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 return db.insert(table, nullColumnHack, values);
138 }
139
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140 @Override
141 public Uri insert(Uri uri, ContentValues initialValues) {
142 SqlArguments args = new SqlArguments(uri);
143
Adam Cohena043fa82014-07-23 14:49:38 -0700144 // In very limited cases, we support system|signature permission apps to add to the db
145 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
146 if (externalAdd != null && "true".equals(externalAdd)) {
147 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
148 return null;
149 }
150 }
151
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400153 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800155 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156
157 uri = ContentUris.withAppendedId(uri, rowId);
158 sendNotify(uri);
159
160 return uri;
161 }
162
Adam Cohena043fa82014-07-23 14:49:38 -0700163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 @Override
165 public int bulkInsert(Uri uri, ContentValues[] values) {
166 SqlArguments args = new SqlArguments(uri);
167
168 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
169 db.beginTransaction();
170 try {
171 int numValues = values.length;
172 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
175 return 0;
176 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177 }
178 db.setTransactionSuccessful();
179 } finally {
180 db.endTransaction();
181 }
182
183 sendNotify(uri);
184 return values.length;
185 }
186
187 @Override
Yura085c8532014-02-11 15:15:29 +0000188 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
189 throws OperationApplicationException {
190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
191 db.beginTransaction();
192 try {
193 ContentProviderResult[] result = super.applyBatch(operations);
194 db.setTransactionSuccessful();
195 return result;
196 } finally {
197 db.endTransaction();
198 }
199 }
200
201 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 public int delete(Uri uri, String selection, String[] selectionArgs) {
203 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
204
205 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
206 int count = db.delete(args.table, args.where, args.args);
207 if (count > 0) sendNotify(uri);
208
209 return count;
210 }
211
212 @Override
213 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
214 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
215
Chris Wren1ada10d2013-09-13 18:01:38 -0400216 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
218 int count = db.update(args.table, values, args.where, args.args);
219 if (count > 0) sendNotify(uri);
220
221 return count;
222 }
223
224 private void sendNotify(Uri uri) {
225 String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
226 if (notify == null || "true".equals(notify)) {
227 getContext().getContentResolver().notifyChange(uri, null);
228 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400229
230 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400231 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700232 if (mListener != null) {
233 mListener.onLauncherProviderChange();
234 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400235 }
236
Adam Cohen091440a2015-03-18 14:16:05 -0700237 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400238 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239 }
240
Adam Cohendcd297f2013-06-18 13:13:40 -0700241 public long generateNewItemId() {
242 return mOpenHelper.generateNewItemId();
243 }
244
Winson Chungc763c4e2013-07-19 13:49:06 -0700245 public void updateMaxItemId(long id) {
246 mOpenHelper.updateMaxItemId(id);
247 }
248
Adam Cohendcd297f2013-06-18 13:13:40 -0700249 public long generateNewScreenId() {
250 return mOpenHelper.generateNewScreenId();
251 }
252
Brian Muramatsu5524b492012-10-02 16:55:54 -0700253 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700254 * Clears all the data for a fresh start.
255 */
256 synchronized public void createEmptyDB() {
257 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
258 }
259
Sunny Goyal33d44382014-10-16 09:24:19 -0700260 public void clearFlagEmptyDbCreated() {
261 String spKey = LauncherAppState.getSharedPreferencesKey();
262 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
263 .edit()
264 .remove(EMPTY_DATABASE_CREATED)
265 .commit();
266 }
267
Sunny Goyal42de82f2014-09-26 22:09:29 -0700268 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700269 * Loads the default workspace based on the following priority scheme:
270 * 1) From a package provided by play store
271 * 2) From a partner configuration APK, already in the system image
272 * 3) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700273 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700274 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400275 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700276 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700277
Winson Chungc763c4e2013-07-19 13:49:06 -0700278 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500279 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200280
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700281 AutoInstallsLayout loader = AutoInstallsLayout.get(getContext(),
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700282 mOpenHelper.mAppWidgetHost, mOpenHelper);
283
284 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700285 final Partner partner = Partner.get(getContext().getPackageManager());
286 if (partner != null && partner.hasDefaultLayout()) {
287 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700288 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700289 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700290 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700291 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
292 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700293 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700294 }
295 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700296
Sunny Goyal9d219682014-10-23 14:21:02 -0700297 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700298 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700299 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700300 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800301
302 // There might be some partially restored DB items, due to buggy restore logic in
303 // previous versions of launcher.
304 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700305 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700306 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
307 && usingExternallyProvidedLayout) {
308 // Unable to load external layout. Cleanup and load the internal layout.
309 createEmptyDB();
310 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
311 getDefaultLayoutParser());
312 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700313 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700314 }
315 }
316
Sunny Goyal9d219682014-10-23 14:21:02 -0700317 private DefaultLayoutParser getDefaultLayoutParser() {
318 int defaultLayout = LauncherAppState.getInstance()
319 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
320 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
321 mOpenHelper, getContext().getResources(), defaultLayout);
322 }
323
Dan Sandlerd5024042014-01-09 15:01:33 -0500324 public void migrateLauncher2Shortcuts() {
325 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400326 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500327 }
328
Sunny Goyal08f72612015-01-05 13:41:43 -0800329 public void updateFolderItemsRank() {
330 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
331 }
332
Dan Sandlerd5024042014-01-09 15:01:33 -0500333 public void deleteDatabase() {
334 // Are you sure? (y/n)
335 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500336 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500337 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500338 if (dbFile.exists()) {
339 SQLiteDatabase.deleteDatabase(dbFile);
340 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500341 mOpenHelper = new DatabaseHelper(getContext());
342 }
343
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700344 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700346 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700347 private long mMaxItemId = -1;
348 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349
Winson Chung0b560dd2014-01-21 13:00:26 -0800350 private boolean mNewDbCreated = false;
351
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100353 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700355 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700356
357 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
358 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700359 if (mMaxItemId == -1) {
360 mMaxItemId = initializeMaxItemId(getWritableDatabase());
361 }
362 if (mMaxScreenId == -1) {
363 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700364 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800365 }
366
Winson Chung0b560dd2014-01-21 13:00:26 -0800367 public boolean wasNewDbCreated() {
368 return mNewDbCreated;
369 }
370
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700371 /**
372 * Send notification that we've deleted the {@link AppWidgetHost},
373 * probably as part of the initial database creation. The receiver may
374 * want to re-call {@link AppWidgetHost#startListening()} to ensure
375 * callbacks are correctly set.
376 */
377 private void sendAppWidgetResetNotify() {
378 final ContentResolver resolver = mContext.getContentResolver();
379 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
380 }
381
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800382 @Override
383 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800384 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700385
Adam Cohendcd297f2013-06-18 13:13:40 -0700386 mMaxItemId = 1;
387 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800388 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700389
Kenny Guyed131872014-04-30 03:02:21 +0100390 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
391 long userSerialNumber = userManager.getSerialNumberForUser(
392 UserHandleCompat.myUserHandle());
393
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800394 db.execSQL("CREATE TABLE favorites (" +
395 "_id INTEGER PRIMARY KEY," +
396 "title TEXT," +
397 "intent TEXT," +
398 "container INTEGER," +
399 "screen INTEGER," +
400 "cellX INTEGER," +
401 "cellY INTEGER," +
402 "spanX INTEGER," +
403 "spanY INTEGER," +
404 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700405 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800406 "isShortcut INTEGER," +
407 "iconType INTEGER," +
408 "iconPackage TEXT," +
409 "iconResource TEXT," +
410 "icon BLOB," +
411 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400412 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400413 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500414 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100415 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800416 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700417 "rank INTEGER NOT NULL DEFAULT 0," +
418 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800419 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700420 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800421
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700422 // Database was just created, so wipe any previous widgets
423 if (mAppWidgetHost != null) {
424 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700425 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800426 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700427
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800428 // Fresh and clean launcher DB.
429 mMaxItemId = initializeMaxItemId(db);
430 setFlagEmptyDbCreated();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800431 }
432
Adam Cohendcd297f2013-06-18 13:13:40 -0700433 private void addWorkspacesTable(SQLiteDatabase db) {
434 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800435 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400436 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
437 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700438 ");");
439 }
440
Adam Cohen119285e2014-04-02 16:59:08 -0700441 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700442 // Delete items directly on the workspace who's screen id doesn't exist
443 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
444 // AND container = -100"
445 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
446 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700447 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700448 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
449 " AND " +
450 LauncherSettings.Favorites.CONTAINER + " = " +
451 LauncherSettings.Favorites.CONTAINER_DESKTOP;
452 db.execSQL(removeOrphanedDesktopItems);
453
454 // Delete items contained in folders which no longer exist (after above statement)
455 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
456 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
457 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
458 " WHERE " +
459 LauncherSettings.Favorites.CONTAINER + " <> " +
460 LauncherSettings.Favorites.CONTAINER_DESKTOP +
461 " AND "
462 + LauncherSettings.Favorites.CONTAINER + " <> " +
463 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
464 " AND "
465 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
466 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
467 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
468 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
469 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700470 }
471
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400473 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700474 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800475 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700476 }
477
Winson Chungc763c4e2013-07-19 13:49:06 -0700478 private void setFlagEmptyDbCreated() {
479 String spKey = LauncherAppState.getSharedPreferencesKey();
480 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800481 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700482 }
483
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800484 @Override
485 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700486 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800487 switch (oldVersion) {
488 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800489 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800490 case 12: {
491 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
492 // to persist workspace screens and their relative order.
493 mMaxScreenId = 0;
494 addWorkspacesTable(db);
495 }
496 case 13: {
497 db.beginTransaction();
498 try {
499 // Insert new column for holding widget provider name
500 db.execSQL("ALTER TABLE favorites " +
501 "ADD COLUMN appWidgetProvider TEXT;");
502 db.setTransactionSuccessful();
503 } catch (SQLException ex) {
504 Log.e(TAG, ex.getMessage(), ex);
505 // Old version remains, which means we wipe old data
506 break;
507 } finally {
508 db.endTransaction();
509 }
510 }
511 case 14: {
512 db.beginTransaction();
513 try {
514 // Insert new column for holding update timestamp
515 db.execSQL("ALTER TABLE favorites " +
516 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
517 db.execSQL("ALTER TABLE workspaceScreens " +
518 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
519 db.setTransactionSuccessful();
520 } catch (SQLException ex) {
521 Log.e(TAG, ex.getMessage(), ex);
522 // Old version remains, which means we wipe old data
523 break;
524 } finally {
525 db.endTransaction();
526 }
527 }
528 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700529 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800530 // Old version remains, which means we wipe old data
531 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800532 }
533 }
534 case 16: {
535 // We use the db version upgrade here to identify users who may not have seen
536 // clings yet (because they weren't available), but for whom the clings are now
537 // available (tablet users). Because one of the possible cling flows (migration)
538 // is very destructive (wipes out workspaces), we want to prevent this from showing
539 // until clear data. We do so by marking that the clings have been shown.
540 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
541 }
542 case 17: {
543 // No-op
544 }
545 case 18: {
546 // Due to a data loss bug, some users may have items associated with screen ids
547 // which no longer exist. Since this can cause other problems, and since the user
548 // will never see these items anyway, we use database upgrade as an opportunity to
549 // clean things up.
550 removeOrphanedItems(db);
551 }
552 case 19: {
553 // Add userId column
554 if (!addProfileColumn(db)) {
555 // Old version remains, which means we wipe old data
556 break;
557 }
558 }
559 case 20:
560 if (!updateFolderItemsRank(db, true)) {
561 break;
562 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800563 case 21:
564 // Recreate workspace table with screen id a primary key
565 if (!recreateWorkspaceTable(db)) {
566 break;
567 }
568 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700569 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
570 // Old version remains, which means we wipe old data
571 break;
572 }
573 }
574 case 23: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800575 // DB Upgraded successfully
576 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400577 }
578 }
579
Sunny Goyala2cc6242015-01-14 14:23:02 -0800580 // DB was not upgraded
581 Log.w(TAG, "Destroying all old data.");
582 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800583 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800584
Adam Cohen9b1d0622014-05-21 19:01:57 -0700585 @Override
586 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
587 // This shouldn't happen -- throw our hands up in the air and start over.
588 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
589 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700590 createEmptyDB(db);
591 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700592
Sunny Goyal42de82f2014-09-26 22:09:29 -0700593
594 /**
595 * Clears all the data for a fresh start.
596 */
597 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700598 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
599 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
600 onCreate(db);
601 }
602
Sunny Goyald2f38192015-02-25 10:46:34 -0800603 /**
604 * Recreates workspace table and migrates data to the new table.
605 */
606 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
607 db.beginTransaction();
608 try {
609 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
610 new String[] {LauncherSettings.WorkspaceScreens._ID},
611 null, null, null, null,
612 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
613 ArrayList<Long> sortedIDs = new ArrayList<Long>();
614 long maxId = 0;
615 try {
616 while (c.moveToNext()) {
617 Long id = c.getLong(0);
618 if (!sortedIDs.contains(id)) {
619 sortedIDs.add(id);
620 maxId = Math.max(maxId, id);
621 }
622 }
623 } finally {
624 c.close();
625 }
626
627 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
628 addWorkspacesTable(db);
629
630 // Add all screen ids back
631 int total = sortedIDs.size();
632 for (int i = 0; i < total; i++) {
633 ContentValues values = new ContentValues();
634 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
635 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
636 addModifiedTime(values);
637 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
638 }
639 db.setTransactionSuccessful();
640 mMaxScreenId = maxId;
641 } catch (SQLException ex) {
642 // Old version remains, which means we wipe old data
643 Log.e(TAG, ex.getMessage(), ex);
644 return false;
645 } finally {
646 db.endTransaction();
647 }
648 return true;
649 }
650
Adam Cohen091440a2015-03-18 14:16:05 -0700651 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800652 db.beginTransaction();
653 try {
654 if (addRankColumn) {
655 // Insert new column for holding rank
656 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
657 }
658
659 // Get a map for folder ID to folder width
660 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
661 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
662 + " GROUP BY container;",
663 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
664
665 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800666 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
667 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800668 new Object[] {c.getLong(1) + 1, c.getLong(0)});
669 }
670
671 c.close();
672 db.setTransactionSuccessful();
673 } catch (SQLException ex) {
674 // Old version remains, which means we wipe old data
675 Log.e(TAG, ex.getMessage(), ex);
676 return false;
677 } finally {
678 db.endTransaction();
679 }
680 return true;
681 }
682
Kenny Guyed131872014-04-30 03:02:21 +0100683 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700684 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
685 // Default to the serial number of this user, for older
686 // shortcuts.
687 long userSerialNumber = userManager.getSerialNumberForUser(
688 UserHandleCompat.myUserHandle());
689 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
690 }
691
692 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100693 db.beginTransaction();
694 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700695 db.execSQL("ALTER TABLE favorites ADD COLUMN "
696 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100697 db.setTransactionSuccessful();
698 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100699 Log.e(TAG, ex.getMessage(), ex);
700 return false;
701 } finally {
702 db.endTransaction();
703 }
704 return true;
705 }
706
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700707 // Generates a new ID to use for an object in your database. This method should be only
708 // called from the main UI thread. As an exception, we do call it when we call the
709 // constructor from the worker thread; however, this doesn't extend until after the
710 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
711 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700712 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 public long generateNewItemId() {
714 if (mMaxItemId < 0) {
715 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700716 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700717 mMaxItemId += 1;
718 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700719 }
720
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700721 @Override
722 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
723 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
724 }
725
Winson Chungc763c4e2013-07-19 13:49:06 -0700726 public void updateMaxItemId(long id) {
727 mMaxItemId = id + 1;
728 }
729
Chris Wren5dee7af2013-12-20 17:22:11 -0500730 public void checkId(String table, ContentValues values) {
731 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
732 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
733 mMaxScreenId = Math.max(id, mMaxScreenId);
734 } else {
735 mMaxItemId = Math.max(id, mMaxItemId);
736 }
737 }
738
Adam Cohendcd297f2013-06-18 13:13:40 -0700739 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800740 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700741 }
742
743 // Generates a new ID to use for an workspace screen in your database. This method
744 // should be only called from the main UI thread. As an exception, we do call it when we
745 // call the constructor from the worker thread; however, this doesn't extend until after the
746 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
747 // after that point
748 public long generateNewScreenId() {
749 if (mMaxScreenId < 0) {
750 throw new RuntimeException("Error: max screen id was not initialized");
751 }
752 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800753 // Log to disk
754 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700755 return mMaxScreenId;
756 }
757
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800759 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800760 }
761
Adam Cohen091440a2015-03-18 14:16:05 -0700762 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700763 // 1. Ensure that externally added items have a valid item id
764 long id = generateNewItemId();
765 values.put(LauncherSettings.Favorites._ID, id);
766
767 // 2. In the case of an app widget, and if no app widget id is specified, we
768 // attempt allocate and bind the widget.
769 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
770 if (itemType != null &&
771 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
772 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
773
774 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
775 ComponentName cn = ComponentName.unflattenFromString(
776 values.getAsString(Favorites.APPWIDGET_PROVIDER));
777
778 if (cn != null) {
779 try {
780 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700781 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700782 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700783 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700784 }
785 } catch (RuntimeException e) {
786 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700787 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700788 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700789 } else {
790 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700791 }
792 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700793
794 // Add screen id if not present
795 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
796 if (!addScreenIdIfNecessary(screenId)) {
797 return false;
798 }
Adam Cohena043fa82014-07-23 14:49:38 -0700799 return true;
800 }
801
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700802 // Returns true of screen id exists, or if successfully added
803 private boolean addScreenIdIfNecessary(long screenId) {
804 if (!hasScreenId(screenId)) {
805 int rank = getMaxScreenRank() + 1;
806
807 ContentValues v = new ContentValues();
808 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
809 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
810 if (dbInsertAndCheck(this, getWritableDatabase(),
811 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
812 return false;
813 }
814 }
815 return true;
816 }
817
818 private boolean hasScreenId(long screenId) {
819 SQLiteDatabase db = getWritableDatabase();
820 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
821 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
822 if (c != null) {
823 int count = c.getCount();
824 c.close();
825 return count > 0;
826 } else {
827 return false;
828 }
829 }
830
831 private int getMaxScreenRank() {
832 SQLiteDatabase db = getWritableDatabase();
833 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
834 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
835
836 // get the result
837 final int maxRankIndex = 0;
838 int rank = -1;
839 if (c != null && c.moveToNext()) {
840 rank = c.getInt(maxRankIndex);
841 }
842 if (c != null) {
843 c.close();
844 }
845
846 return rank;
847 }
848
Adam Cohen091440a2015-03-18 14:16:05 -0700849 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700850 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700851 // TODO: Use multiple loaders with fall-back and transaction.
852 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700853
854 // Add the screens specified by the items above
855 Collections.sort(screenIds);
856 int rank = 0;
857 ContentValues values = new ContentValues();
858 for (Long id : screenIds) {
859 values.clear();
860 values.put(LauncherSettings.WorkspaceScreens._ID, id);
861 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
862 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
863 throw new RuntimeException("Failed initialize screen table"
864 + "from default layout");
865 }
866 rank++;
867 }
868
869 // Ensure that the max ids are initialized
870 mMaxItemId = initializeMaxItemId(db);
871 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700872
Adam Cohen71483f42014-05-15 14:04:01 -0700873 return count;
874 }
875
Adam Cohen091440a2015-03-18 14:16:05 -0700876 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500877 final ContentResolver resolver = mContext.getContentResolver();
878 Cursor c = null;
879 int count = 0;
880 int curScreen = 0;
881
882 try {
883 c = resolver.query(uri, null, null, null, "title ASC");
884 } catch (Exception e) {
885 // Ignore
886 }
887
Dan Sandlerd5024042014-01-09 15:01:33 -0500888 // We already have a favorites database in the old provider
889 if (c != null) {
890 try {
891 if (c.getCount() > 0) {
892 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
893 final int intentIndex
894 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
895 final int titleIndex
896 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
897 final int iconTypeIndex
898 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
899 final int iconIndex
900 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
901 final int iconPackageIndex
902 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
903 final int iconResourceIndex
904 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
905 final int containerIndex
906 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
907 final int itemTypeIndex
908 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
909 final int screenIndex
910 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
911 final int cellXIndex
912 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
913 final int cellYIndex
914 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
915 final int uriIndex
916 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
917 final int displayModeIndex
918 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +0100919 final int profileIndex
920 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -0500921
922 int i = 0;
923 int curX = 0;
924 int curY = 0;
925
926 final LauncherAppState app = LauncherAppState.getInstance();
927 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
928 final int width = (int) grid.numColumns;
929 final int height = (int) grid.numRows;
930 final int hotseatWidth = (int) grid.numHotseatIcons;
931
932 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
933
Adam Cohen72960972014-01-15 18:13:55 -0800934 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
935 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500936 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -0500937
938 while (c.moveToNext()) {
939 final int itemType = c.getInt(itemTypeIndex);
940 if (itemType != Favorites.ITEM_TYPE_APPLICATION
941 && itemType != Favorites.ITEM_TYPE_SHORTCUT
942 && itemType != Favorites.ITEM_TYPE_FOLDER) {
943 continue;
944 }
945
946 final int cellX = c.getInt(cellXIndex);
947 final int cellY = c.getInt(cellYIndex);
948 final int screen = c.getInt(screenIndex);
949 int container = c.getInt(containerIndex);
950 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100951
952 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
953 UserHandleCompat userHandle;
954 final long userSerialNumber;
955 if (profileIndex != -1 && !c.isNull(profileIndex)) {
956 userSerialNumber = c.getInt(profileIndex);
957 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
958 } else {
959 // Default to the serial number of this user, for older
960 // shortcuts.
961 userHandle = UserHandleCompat.myUserHandle();
962 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
963 }
Sunny Goyal416541c2014-11-14 11:59:57 -0800964
965 if (userHandle == null) {
966 Launcher.addDumpLog(TAG, "skipping deleted user", true);
967 continue;
968 }
969
Dan Sandlerd5024042014-01-09 15:01:33 -0500970 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -0500971 + c.getString(titleIndex) + "\" ("
972 + cellX + "," + cellY + "@"
973 + LauncherSettings.Favorites.containerToString(container)
974 + "/" + screen
975 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -0500976
977 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -0800978
979 final Intent intent;
980 final ComponentName cn;
981 try {
982 intent = Intent.parseUri(intentStr, 0);
983 } catch (URISyntaxException e) {
984 // bogus intent?
985 Launcher.addDumpLog(TAG,
986 "skipping invalid intent uri", true);
987 continue;
988 }
989
990 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -0500991 if (TextUtils.isEmpty(intentStr)) {
992 // no intent? no icon
993 Launcher.addDumpLog(TAG, "skipping empty intent", true);
994 continue;
Adam Cohen72960972014-01-15 18:13:55 -0800995 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +0100996 !LauncherModel.isValidPackageActivity(mContext, cn,
997 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -0800998 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -0800999 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001000 "no longer exists.", true);
1001 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001002 } else if (container ==
1003 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1004 // Dedupe icons directly on the workspace
1005
Adam Cohen556f6132014-01-15 15:18:08 -08001006 // Canonicalize
1007 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001008 // does not, so we clear that out to keep them the same.
1009 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001010 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001011 int flags = intent.getFlags();
1012 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001013 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001014 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001015 if (seenIntents.contains(key)) {
1016 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001017 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001018 } else {
1019 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001020 }
1021 }
1022 }
1023
1024 ContentValues values = new ContentValues(c.getColumnCount());
1025 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1026 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1027 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1028 values.put(LauncherSettings.Favorites.ICON_TYPE,
1029 c.getInt(iconTypeIndex));
1030 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1031 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1032 c.getString(iconPackageIndex));
1033 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1034 c.getString(iconResourceIndex));
1035 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1036 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1037 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1038 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1039 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001040 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001041
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001042 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1043 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001044 }
1045
1046 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1047 // In a folder or in the hotseat, preserve position
1048 values.put(LauncherSettings.Favorites.SCREEN, screen);
1049 values.put(LauncherSettings.Favorites.CELLX, cellX);
1050 values.put(LauncherSettings.Favorites.CELLY, cellY);
1051 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001052 // For items contained directly on one of the workspace screen,
1053 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001054 }
1055
1056 values.put(LauncherSettings.Favorites.CONTAINER, container);
1057
Adam Cohen72960972014-01-15 18:13:55 -08001058 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1059 shortcuts.add(values);
1060 } else {
1061 folders.add(values);
1062 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001063 }
1064
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001065 // Now that we have all the hotseat icons, let's go through them left-right
1066 // and assign valid locations for them in the new hotseat
1067 final int N = hotseat.size();
1068 for (int idx=0; idx<N; idx++) {
1069 int hotseatX = hotseat.keyAt(idx);
1070 ContentValues values = hotseat.valueAt(idx);
1071
1072 if (hotseatX == grid.hotseatAllAppsRank) {
1073 // let's drop this in the next available hole in the hotseat
1074 while (++hotseatX < hotseatWidth) {
1075 if (hotseat.get(hotseatX) == null) {
1076 // found a spot! move it here
1077 values.put(LauncherSettings.Favorites.SCREEN,
1078 hotseatX);
1079 break;
1080 }
1081 }
1082 }
1083 if (hotseatX >= hotseatWidth) {
1084 // no room for you in the hotseat? it's off to the desktop with you
1085 values.put(LauncherSettings.Favorites.CONTAINER,
1086 Favorites.CONTAINER_DESKTOP);
1087 }
1088 }
1089
Adam Cohen72960972014-01-15 18:13:55 -08001090 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1091 // Folders first
1092 allItems.addAll(folders);
1093 // Then shortcuts
1094 allItems.addAll(shortcuts);
1095
1096 // Layout all the folders
1097 for (ContentValues values: allItems) {
1098 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1099 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1100 // Hotseat items and folder items have already had their
1101 // location information set. Nothing to be done here.
1102 continue;
1103 }
1104 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1105 values.put(LauncherSettings.Favorites.CELLX, curX);
1106 values.put(LauncherSettings.Favorites.CELLY, curY);
1107 curX = (curX + 1) % width;
1108 if (curX == 0) {
1109 curY = (curY + 1);
1110 }
1111 // Leave the last row of icons blank on every screen
1112 if (curY == height - 1) {
1113 curScreen = (int) generateNewScreenId();
1114 curY = 0;
1115 }
1116 }
1117
1118 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001119 db.beginTransaction();
1120 try {
Adam Cohen72960972014-01-15 18:13:55 -08001121 for (ContentValues row: allItems) {
1122 if (row == null) continue;
1123 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001124 < 0) {
1125 return;
1126 } else {
1127 count++;
1128 }
1129 }
1130 db.setTransactionSuccessful();
1131 } finally {
1132 db.endTransaction();
1133 }
1134 }
1135
1136 db.beginTransaction();
1137 try {
1138 for (i=0; i<=curScreen; i++) {
1139 final ContentValues values = new ContentValues();
1140 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1141 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1142 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1143 < 0) {
1144 return;
1145 }
1146 }
1147 db.setTransactionSuccessful();
1148 } finally {
1149 db.endTransaction();
1150 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001151
1152 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001153 }
1154 } finally {
1155 c.close();
1156 }
1157 }
1158
1159 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1160 + (curScreen+1) + " screens", true);
1161
1162 // ensure that new screens are created to hold these icons
1163 setFlagJustLoadedOldDb();
1164
1165 // Update max IDs; very important since we just grabbed IDs from another database
1166 mMaxItemId = initializeMaxItemId(db);
1167 mMaxScreenId = initializeMaxScreenId(db);
1168 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1169 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001170 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001171
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001172 /**
1173 * @return the max _id in the provided table.
1174 */
Adam Cohen091440a2015-03-18 14:16:05 -07001175 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001176 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1177 // get the result
1178 long id = -1;
1179 if (c != null && c.moveToNext()) {
1180 id = c.getLong(0);
1181 }
1182 if (c != null) {
1183 c.close();
1184 }
1185
1186 if (id == -1) {
1187 throw new RuntimeException("Error: could not query max id in " + table);
1188 }
1189
1190 return id;
1191 }
1192
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 static class SqlArguments {
1194 public final String table;
1195 public final String where;
1196 public final String[] args;
1197
1198 SqlArguments(Uri url, String where, String[] args) {
1199 if (url.getPathSegments().size() == 1) {
1200 this.table = url.getPathSegments().get(0);
1201 this.where = where;
1202 this.args = args;
1203 } else if (url.getPathSegments().size() != 2) {
1204 throw new IllegalArgumentException("Invalid URI: " + url);
1205 } else if (!TextUtils.isEmpty(where)) {
1206 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1207 } else {
1208 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001209 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001210 this.args = null;
1211 }
1212 }
1213
1214 SqlArguments(Uri url) {
1215 if (url.getPathSegments().size() == 1) {
1216 table = url.getPathSegments().get(0);
1217 where = null;
1218 args = null;
1219 } else {
1220 throw new IllegalArgumentException("Invalid URI: " + url);
1221 }
1222 }
1223 }
Adam Cohen72960972014-01-15 18:13:55 -08001224}