blob: 261292d69969c905f62d213b0d376f9e68e44c70 [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;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080046import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050050import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070067 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080068 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Sunny Goyale5bb7052015-07-27 14:36:07 -070072 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070073
Sunny Goyal18b640c2015-04-17 09:24:01 -070074 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
75 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080076 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070078 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
79
Sunny Goyald3849d12015-10-29 10:28:32 -070080 private static final Object LISTENER_LOCK = new Object();
Sunny Goyal383c5072015-06-12 21:18:53 -070081 @Thunk LauncherProviderChangeListener mListener;
Sunny Goyal316490e2015-06-02 09:38:28 -070082 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84 @Override
85 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040086 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 return true;
88 }
89
Sunny Goyald3849d12015-10-29 10:28:32 -070090 /**
91 * Sets a provider listener.
92 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -070093 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyald3849d12015-10-29 10:28:32 -070094 synchronized (LISTENER_LOCK) {
95 mListener = listener;
96 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -070097 }
98
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099 @Override
100 public String getType(Uri uri) {
101 SqlArguments args = new SqlArguments(uri, null, null);
102 if (TextUtils.isEmpty(args.where)) {
103 return "vnd.android.cursor.dir/" + args.table;
104 } else {
105 return "vnd.android.cursor.item/" + args.table;
106 }
107 }
108
Sunny Goyald3849d12015-10-29 10:28:32 -0700109 private synchronized void createDbIfNotExists() {
110 if (mOpenHelper == null) {
111 mOpenHelper = new DatabaseHelper(getContext(), this);
112 }
113 }
114
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115 @Override
116 public Cursor query(Uri uri, String[] projection, String selection,
117 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700118 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119
120 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
121 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
122 qb.setTables(args.table);
123
Romain Guy73b979d2009-06-09 12:57:21 -0700124 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
126 result.setNotificationUri(getContext().getContentResolver(), uri);
127
128 return result;
129 }
130
Adam Cohen091440a2015-03-18 14:16:05 -0700131 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700132 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500133 if (values == null) {
134 throw new RuntimeException("Error: attempting to insert null values");
135 }
Adam Cohen71483f42014-05-15 14:04:01 -0700136 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 throw new RuntimeException("Error: attempting to add item without specifying an id");
138 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500139 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 return db.insert(table, nullColumnHack, values);
141 }
142
Sunny Goyald1064182015-08-13 12:08:30 -0700143 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700144 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700145 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
146 if (app != null) {
147 app.reloadWorkspace();
148 }
149 }
150 }
151
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152 @Override
153 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700154 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 SqlArguments args = new SqlArguments(uri);
156
Sunny Goyald1064182015-08-13 12:08:30 -0700157 // In very limited cases, we support system|signature permission apps to modify the db.
158 if (Binder.getCallingPid() != Process.myPid()) {
Adam Cohena043fa82014-07-23 14:49:38 -0700159 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
160 return null;
161 }
162 }
163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400165 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700166 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800167 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168
169 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700170 notifyListeners();
171
Sunny Goyalc74e4192015-09-08 14:01:03 -0700172 if (Utilities.ATLEAST_MARSHMALLOW) {
173 reloadLauncherIfExternal();
174 } else {
175 // Deprecated behavior to support legacy devices which rely on provider callbacks.
176 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
177 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
178 app.reloadWorkspace();
179 }
180
181 String notify = uri.getQueryParameter("notify");
182 if (notify == null || "true".equals(notify)) {
183 getContext().getContentResolver().notifyChange(uri, null);
184 }
185 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186 return uri;
187 }
188
189 @Override
190 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700191 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 SqlArguments args = new SqlArguments(uri);
193
194 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
195 db.beginTransaction();
196 try {
197 int numValues = values.length;
198 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400199 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700200 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
201 return 0;
202 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 }
204 db.setTransactionSuccessful();
205 } finally {
206 db.endTransaction();
207 }
208
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700209 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700210 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 return values.length;
212 }
213
214 @Override
Yura085c8532014-02-11 15:15:29 +0000215 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
216 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700217 createDbIfNotExists();
Yura085c8532014-02-11 15:15:29 +0000218 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
219 db.beginTransaction();
220 try {
221 ContentProviderResult[] result = super.applyBatch(operations);
222 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700223 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000224 return result;
225 } finally {
226 db.endTransaction();
227 }
228 }
229
230 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700232 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
234
235 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
236 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700237 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238
Sunny Goyald1064182015-08-13 12:08:30 -0700239 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240 return count;
241 }
242
243 @Override
244 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700245 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
247
Chris Wren1ada10d2013-09-13 18:01:38 -0400248 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800249 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
250 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700251 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800252
Sunny Goyald1064182015-08-13 12:08:30 -0700253 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800254 return count;
255 }
256
Sunny Goyal7779d622015-06-11 16:18:39 -0700257 @Override
258 public Bundle call(String method, String arg, Bundle extras) {
259 if (Binder.getCallingUid() != Process.myUid()) {
260 return null;
261 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700262 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700263
264 switch (method) {
265 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
266 Bundle result = new Bundle();
267 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700268 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
269 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700270 return result;
271 }
272 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
273 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700274 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyald3849d12015-10-29 10:28:32 -0700275 synchronized (LISTENER_LOCK) {
276 if (mListener != null) {
277 mListener.onSettingsChanged(arg, value);
278 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700279 }
280 Bundle result = new Bundle();
281 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
282 return result;
283 }
Sunny Goyald2497482015-09-22 18:24:19 -0700284 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
285 clearFlagEmptyDbCreated();
286 return null;
287 }
288 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
289 Bundle result = new Bundle();
290 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
291 return result;
292 }
293 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
294 Bundle result = new Bundle();
295 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
296 return result;
297 }
298 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
299 Bundle result = new Bundle();
300 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
301 return result;
302 }
303 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
304 createEmptyDB();
305 return null;
306 }
307 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
308 loadDefaultFavoritesIfNecessary();
309 return null;
310 }
311 case LauncherSettings.Settings.METHOD_MIGRATE_LAUNCHER2_SHORTCUTS: {
312 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
313 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
314 return null;
315 }
316 case LauncherSettings.Settings.METHOD_UPDATE_FOLDER_ITEMS_RANK: {
317 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
318 return null;
319 }
320 case LauncherSettings.Settings.METHOD_CONVERT_SHORTCUTS_TO_ACTIVITIES: {
321 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
322 return null;
323 }
324 case LauncherSettings.Settings.METHOD_DELETE_DB: {
325 deleteDatabase();
326 return null;
327 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700328 }
329 return null;
330 }
331
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700332 /**
333 * Deletes any empty folder from the DB.
334 * @return Ids of deleted folders.
335 */
Sunny Goyald2497482015-09-22 18:24:19 -0700336 private ArrayList<Long> deleteEmptyFolders() {
337 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700338 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
339 db.beginTransaction();
340 try {
341 // Select folders whose id do not match any container value.
342 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
343 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
344 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
345 LauncherSettings.Favorites.CONTAINER + " FROM "
346 + TABLE_FAVORITES + ")";
347 Cursor c = db.query(TABLE_FAVORITES,
348 new String[] {LauncherSettings.Favorites._ID},
349 selection, null, null, null, null);
350 while (c.moveToNext()) {
351 folderIds.add(c.getLong(0));
352 }
353 c.close();
Sunny Goyald2497482015-09-22 18:24:19 -0700354 if (!folderIds.isEmpty()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700355 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
356 LauncherSettings.Favorites._ID, folderIds), null);
357 }
358 db.setTransactionSuccessful();
359 } catch (SQLException ex) {
360 Log.e(TAG, ex.getMessage(), ex);
361 folderIds.clear();
362 } finally {
363 db.endTransaction();
364 }
365 return folderIds;
366 }
367
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700368 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400369 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400370 LauncherBackupAgentHelper.dataChanged(getContext());
Sunny Goyald3849d12015-10-29 10:28:32 -0700371 synchronized (LISTENER_LOCK) {
372 if (mListener != null) {
373 mListener.onLauncherProviderChange();
374 }
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700375 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400376 }
377
Adam Cohen091440a2015-03-18 14:16:05 -0700378 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400379 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800380 }
381
Brian Muramatsu5524b492012-10-02 16:55:54 -0700382 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700383 * Clears all the data for a fresh start.
384 */
Sunny Goyald2497482015-09-22 18:24:19 -0700385 synchronized private void createEmptyDB() {
Sunny Goyal42de82f2014-09-26 22:09:29 -0700386 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
387 }
388
Sunny Goyald2497482015-09-22 18:24:19 -0700389 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700390 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700391 }
392
Sunny Goyal42de82f2014-09-26 22:09:29 -0700393 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700394 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700395 * 1) From the app restrictions
396 * 2) From a package provided by play store
397 * 3) From a partner configuration APK, already in the system image
398 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700399 */
Sunny Goyald2497482015-09-22 18:24:19 -0700400 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700401 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700402
Winson Chungc763c4e2013-07-19 13:49:06 -0700403 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500404 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200405
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700406 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
407 if (loader == null) {
408 loader = AutoInstallsLayout.get(getContext(),
409 mOpenHelper.mAppWidgetHost, mOpenHelper);
410 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700411 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700412 final Partner partner = Partner.get(getContext().getPackageManager());
413 if (partner != null && partner.hasDefaultLayout()) {
414 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700415 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700416 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700417 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700418 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
419 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700420 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700421 }
422 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700423
Sunny Goyal9d219682014-10-23 14:21:02 -0700424 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700425 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700426 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700427 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800428
429 // There might be some partially restored DB items, due to buggy restore logic in
430 // previous versions of launcher.
431 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700432 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700433 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
434 && usingExternallyProvidedLayout) {
435 // Unable to load external layout. Cleanup and load the internal layout.
436 createEmptyDB();
437 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
438 getDefaultLayoutParser());
439 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700440 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700441 }
442 }
443
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700444 /**
445 * Creates workspace loader from an XML resource listed in the app restrictions.
446 *
447 * @return the loader if the restrictions are set and the resource exists; null otherwise.
448 */
449 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
450 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
451 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700452 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700453 return null;
454 }
455
456 Context ctx = getContext();
457 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
458 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700459 if (bundle == null) {
460 return null;
461 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700462
Sunny Goyal35ca8732015-04-06 10:45:31 -0700463 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700464 if (packageName != null) {
465 try {
466 Resources targetResources = ctx.getPackageManager()
467 .getResourcesForApplication(packageName);
468 return AutoInstallsLayout.get(ctx, packageName, targetResources,
469 mOpenHelper.mAppWidgetHost, mOpenHelper);
470 } catch (NameNotFoundException e) {
471 Log.e(TAG, "Target package for restricted profile not found", e);
472 return null;
473 }
474 }
475 return null;
476 }
477
Sunny Goyal9d219682014-10-23 14:21:02 -0700478 private DefaultLayoutParser getDefaultLayoutParser() {
479 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700480 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700481 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
482 mOpenHelper, getContext().getResources(), defaultLayout);
483 }
484
Sunny Goyald2497482015-09-22 18:24:19 -0700485 private void deleteDatabase() {
Dan Sandlerd5024042014-01-09 15:01:33 -0500486 // Are you sure? (y/n)
487 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500488 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500489 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500490 if (dbFile.exists()) {
491 SQLiteDatabase.deleteDatabase(dbFile);
492 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700493 mOpenHelper = new DatabaseHelper(getContext(), this);
494 }
495
496 /**
497 * Send notification that we've deleted the {@link AppWidgetHost},
498 * probably as part of the initial database creation. The receiver may
499 * want to re-call {@link AppWidgetHost#startListening()} to ensure
500 * callbacks are correctly set.
501 */
502 @Thunk void notifyAppHostReset() {
503 new MainThreadExecutor().execute(new Runnable() {
504
505 @Override
506 public void run() {
507 synchronized (LISTENER_LOCK) {
508 if (mListener != null) {
509 mListener.onAppWidgetHostReset();
510 }
511 }
512 }
513 });
Dan Sandlerd5024042014-01-09 15:01:33 -0500514 }
515
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700516 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyald3849d12015-10-29 10:28:32 -0700517 private final LauncherProvider mProvider;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700519 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700520 private long mMaxItemId = -1;
521 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800522
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 DatabaseHelper(Context context, LauncherProvider provider) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100524 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800525 mContext = context;
Sunny Goyald3849d12015-10-29 10:28:32 -0700526 mProvider = provider;
527
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700528 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700529
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700530 // Table creation sometimes fails silently, which leads to a crash loop.
531 // This way, we will try to create a table every time after crash, so the device
532 // would eventually be able to recover.
533 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
534 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
535 // This operation is a no-op if the table already exists.
536 addFavoritesTable(getWritableDatabase(), true);
537 addWorkspacesTable(getWritableDatabase(), true);
538 }
539
Winson Chung3d503fb2011-07-13 17:25:49 -0700540 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
541 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700542 if (mMaxItemId == -1) {
543 mMaxItemId = initializeMaxItemId(getWritableDatabase());
544 }
545 if (mMaxScreenId == -1) {
546 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700547 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 }
549
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700550 private boolean tableExists(String tableName) {
551 Cursor c = getReadableDatabase().query(
552 true, "sqlite_master", new String[] {"tbl_name"},
553 "tbl_name = ?", new String[] {tableName},
554 null, null, null, null, null);
555 try {
556 return c.getCount() > 0;
557 } finally {
558 c.close();
559 }
560 }
561
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800562 @Override
563 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800564 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700565
Adam Cohendcd297f2013-06-18 13:13:40 -0700566 mMaxItemId = 1;
567 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700568
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700569 addFavoritesTable(db, false);
570 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800571
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700572 // Database was just created, so wipe any previous widgets
573 if (mAppWidgetHost != null) {
574 mAppWidgetHost.deleteHost();
Sunny Goyald3849d12015-10-29 10:28:32 -0700575 mProvider.notifyAppHostReset();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800576 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700577
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800578 // Fresh and clean launcher DB.
579 mMaxItemId = initializeMaxItemId(db);
580 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700581
582 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700583 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 }
585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
587 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
588 long userSerialNumber = userManager.getSerialNumberForUser(
589 UserHandleCompat.myUserHandle());
590 String ifNotExists = optional ? " IF NOT EXISTS " : "";
591
592 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
593 "_id INTEGER PRIMARY KEY," +
594 "title TEXT," +
595 "intent TEXT," +
596 "container INTEGER," +
597 "screen INTEGER," +
598 "cellX INTEGER," +
599 "cellY INTEGER," +
600 "spanX INTEGER," +
601 "spanY INTEGER," +
602 "itemType INTEGER," +
603 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
604 "isShortcut INTEGER," +
605 "iconType INTEGER," +
606 "iconPackage TEXT," +
607 "iconResource TEXT," +
608 "icon BLOB," +
609 "uri TEXT," +
610 "displayMode INTEGER," +
611 "appWidgetProvider TEXT," +
612 "modified INTEGER NOT NULL DEFAULT 0," +
613 "restored INTEGER NOT NULL DEFAULT 0," +
614 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
615 "rank INTEGER NOT NULL DEFAULT 0," +
616 "options INTEGER NOT NULL DEFAULT 0" +
617 ");");
618 }
619
620 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
621 String ifNotExists = optional ? " IF NOT EXISTS " : "";
622 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800623 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400624 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
625 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700626 ");");
627 }
628
Adam Cohen119285e2014-04-02 16:59:08 -0700629 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700630 // Delete items directly on the workspace who's screen id doesn't exist
631 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
632 // AND container = -100"
633 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
634 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700635 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700636 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
637 " AND " +
638 LauncherSettings.Favorites.CONTAINER + " = " +
639 LauncherSettings.Favorites.CONTAINER_DESKTOP;
640 db.execSQL(removeOrphanedDesktopItems);
641
642 // Delete items contained in folders which no longer exist (after above statement)
643 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
644 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
645 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
646 " WHERE " +
647 LauncherSettings.Favorites.CONTAINER + " <> " +
648 LauncherSettings.Favorites.CONTAINER_DESKTOP +
649 " AND "
650 + LauncherSettings.Favorites.CONTAINER + " <> " +
651 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
652 " AND "
653 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
654 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
655 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
656 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
657 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700658 }
659
Winson Chungc763c4e2013-07-19 13:49:06 -0700660 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700661 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700662 }
663
Winson Chungc763c4e2013-07-19 13:49:06 -0700664 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700665 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700666 }
667
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 @Override
669 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700670 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 switch (oldVersion) {
672 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800673 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800674 case 12: {
675 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
676 // to persist workspace screens and their relative order.
677 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700678 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800679 }
680 case 13: {
681 db.beginTransaction();
682 try {
683 // Insert new column for holding widget provider name
684 db.execSQL("ALTER TABLE favorites " +
685 "ADD COLUMN appWidgetProvider TEXT;");
686 db.setTransactionSuccessful();
687 } catch (SQLException ex) {
688 Log.e(TAG, ex.getMessage(), ex);
689 // Old version remains, which means we wipe old data
690 break;
691 } finally {
692 db.endTransaction();
693 }
694 }
695 case 14: {
696 db.beginTransaction();
697 try {
698 // Insert new column for holding update timestamp
699 db.execSQL("ALTER TABLE favorites " +
700 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
701 db.execSQL("ALTER TABLE workspaceScreens " +
702 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
703 db.setTransactionSuccessful();
704 } catch (SQLException ex) {
705 Log.e(TAG, ex.getMessage(), ex);
706 // Old version remains, which means we wipe old data
707 break;
708 } finally {
709 db.endTransaction();
710 }
711 }
712 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700713 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800714 // Old version remains, which means we wipe old data
715 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 }
717 }
718 case 16: {
719 // We use the db version upgrade here to identify users who may not have seen
720 // clings yet (because they weren't available), but for whom the clings are now
721 // available (tablet users). Because one of the possible cling flows (migration)
722 // is very destructive (wipes out workspaces), we want to prevent this from showing
723 // until clear data. We do so by marking that the clings have been shown.
724 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
725 }
726 case 17: {
727 // No-op
728 }
729 case 18: {
730 // Due to a data loss bug, some users may have items associated with screen ids
731 // which no longer exist. Since this can cause other problems, and since the user
732 // will never see these items anyway, we use database upgrade as an opportunity to
733 // clean things up.
734 removeOrphanedItems(db);
735 }
736 case 19: {
737 // Add userId column
738 if (!addProfileColumn(db)) {
739 // Old version remains, which means we wipe old data
740 break;
741 }
742 }
743 case 20:
744 if (!updateFolderItemsRank(db, true)) {
745 break;
746 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800747 case 21:
748 // Recreate workspace table with screen id a primary key
749 if (!recreateWorkspaceTable(db)) {
750 break;
751 }
752 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700753 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
754 // Old version remains, which means we wipe old data
755 break;
756 }
757 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700758 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700759 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700760 case 24:
761 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700762 case 25:
763 convertShortcutsToLauncherActivities(db);
764 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800765 // DB Upgraded successfully
766 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400767 }
768 }
769
Sunny Goyala2cc6242015-01-14 14:23:02 -0800770 // DB was not upgraded
771 Log.w(TAG, "Destroying all old data.");
772 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800773 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800774
Adam Cohen9b1d0622014-05-21 19:01:57 -0700775 @Override
776 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
777 // This shouldn't happen -- throw our hands up in the air and start over.
778 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
779 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700780 createEmptyDB(db);
781 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700782
Sunny Goyal42de82f2014-09-26 22:09:29 -0700783 /**
784 * Clears all the data for a fresh start.
785 */
786 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700787 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
788 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
789 onCreate(db);
790 }
791
Sunny Goyald2f38192015-02-25 10:46:34 -0800792 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700793 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
794 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
795 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700796 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700797 db.beginTransaction();
798 Cursor c = null;
799 SQLiteStatement updateStmt = null;
800
801 try {
802 // Only consider the primary user as other users can't have a shortcut.
803 long userSerial = UserManagerCompat.getInstance(mContext)
804 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
805 c = db.query(TABLE_FAVORITES, new String[] {
806 Favorites._ID,
807 Favorites.INTENT,
808 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
809 null, null, null, null);
810
811 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
812 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
813
814 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
815 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
816
817 while (c.moveToNext()) {
818 String intentDescription = c.getString(intentIndex);
819 Intent intent;
820 try {
821 intent = Intent.parseUri(intentDescription, 0);
822 } catch (URISyntaxException e) {
823 Log.e(TAG, "Unable to parse intent", e);
824 continue;
825 }
826
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700827 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700828 continue;
829 }
830
831 long id = c.getLong(idIndex);
832 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700833 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700834 }
835 db.setTransactionSuccessful();
836 } catch (SQLException ex) {
837 Log.w(TAG, "Error deduping shortcuts", ex);
838 } finally {
839 db.endTransaction();
840 if (c != null) {
841 c.close();
842 }
843 if (updateStmt != null) {
844 updateStmt.close();
845 }
846 }
847 }
848
849 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800850 * Recreates workspace table and migrates data to the new table.
851 */
852 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
853 db.beginTransaction();
854 try {
855 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
856 new String[] {LauncherSettings.WorkspaceScreens._ID},
857 null, null, null, null,
858 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
859 ArrayList<Long> sortedIDs = new ArrayList<Long>();
860 long maxId = 0;
861 try {
862 while (c.moveToNext()) {
863 Long id = c.getLong(0);
864 if (!sortedIDs.contains(id)) {
865 sortedIDs.add(id);
866 maxId = Math.max(maxId, id);
867 }
868 }
869 } finally {
870 c.close();
871 }
872
873 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700874 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800875
876 // Add all screen ids back
877 int total = sortedIDs.size();
878 for (int i = 0; i < total; i++) {
879 ContentValues values = new ContentValues();
880 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
881 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
882 addModifiedTime(values);
883 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
884 }
885 db.setTransactionSuccessful();
886 mMaxScreenId = maxId;
887 } catch (SQLException ex) {
888 // Old version remains, which means we wipe old data
889 Log.e(TAG, ex.getMessage(), ex);
890 return false;
891 } finally {
892 db.endTransaction();
893 }
894 return true;
895 }
896
Adam Cohen091440a2015-03-18 14:16:05 -0700897 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800898 db.beginTransaction();
899 try {
900 if (addRankColumn) {
901 // Insert new column for holding rank
902 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
903 }
904
905 // Get a map for folder ID to folder width
906 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
907 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
908 + " GROUP BY container;",
909 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
910
911 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800912 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
913 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800914 new Object[] {c.getLong(1) + 1, c.getLong(0)});
915 }
916
917 c.close();
918 db.setTransactionSuccessful();
919 } catch (SQLException ex) {
920 // Old version remains, which means we wipe old data
921 Log.e(TAG, ex.getMessage(), ex);
922 return false;
923 } finally {
924 db.endTransaction();
925 }
926 return true;
927 }
928
Kenny Guyed131872014-04-30 03:02:21 +0100929 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700930 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
931 // Default to the serial number of this user, for older
932 // shortcuts.
933 long userSerialNumber = userManager.getSerialNumberForUser(
934 UserHandleCompat.myUserHandle());
935 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
936 }
937
938 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100939 db.beginTransaction();
940 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700941 db.execSQL("ALTER TABLE favorites ADD COLUMN "
942 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100943 db.setTransactionSuccessful();
944 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100945 Log.e(TAG, ex.getMessage(), ex);
946 return false;
947 } finally {
948 db.endTransaction();
949 }
950 return true;
951 }
952
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700953 // Generates a new ID to use for an object in your database. This method should be only
954 // called from the main UI thread. As an exception, we do call it when we call the
955 // constructor from the worker thread; however, this doesn't extend until after the
956 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
957 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700958 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700959 public long generateNewItemId() {
960 if (mMaxItemId < 0) {
961 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700962 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700963 mMaxItemId += 1;
964 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700965 }
966
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700967 @Override
968 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
969 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
970 }
971
Chris Wren5dee7af2013-12-20 17:22:11 -0500972 public void checkId(String table, ContentValues values) {
973 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
974 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
975 mMaxScreenId = Math.max(id, mMaxScreenId);
976 } else {
977 mMaxItemId = Math.max(id, mMaxItemId);
978 }
979 }
980
Adam Cohendcd297f2013-06-18 13:13:40 -0700981 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800982 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 }
984
985 // Generates a new ID to use for an workspace screen in your database. This method
986 // should be only called from the main UI thread. As an exception, we do call it when we
987 // call the constructor from the worker thread; however, this doesn't extend until after the
988 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
989 // after that point
990 public long generateNewScreenId() {
991 if (mMaxScreenId < 0) {
992 throw new RuntimeException("Error: max screen id was not initialized");
993 }
994 mMaxScreenId += 1;
995 return mMaxScreenId;
996 }
997
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800999 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -08001000 }
1001
Adam Cohen091440a2015-03-18 14:16:05 -07001002 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -07001003 // 1. Ensure that externally added items have a valid item id
1004 long id = generateNewItemId();
1005 values.put(LauncherSettings.Favorites._ID, id);
1006
1007 // 2. In the case of an app widget, and if no app widget id is specified, we
1008 // attempt allocate and bind the widget.
1009 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
1010 if (itemType != null &&
1011 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
1012 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
1013
1014 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
1015 ComponentName cn = ComponentName.unflattenFromString(
1016 values.getAsString(Favorites.APPWIDGET_PROVIDER));
1017
1018 if (cn != null) {
1019 try {
1020 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -07001021 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -07001022 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -07001023 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001024 }
1025 } catch (RuntimeException e) {
1026 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -07001027 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001028 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001029 } else {
1030 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001031 }
1032 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001033
1034 // Add screen id if not present
1035 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1036 if (!addScreenIdIfNecessary(screenId)) {
1037 return false;
1038 }
Adam Cohena043fa82014-07-23 14:49:38 -07001039 return true;
1040 }
1041
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001042 // Returns true of screen id exists, or if successfully added
1043 private boolean addScreenIdIfNecessary(long screenId) {
1044 if (!hasScreenId(screenId)) {
1045 int rank = getMaxScreenRank() + 1;
1046
1047 ContentValues v = new ContentValues();
1048 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1049 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1050 if (dbInsertAndCheck(this, getWritableDatabase(),
1051 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1052 return false;
1053 }
1054 }
1055 return true;
1056 }
1057
1058 private boolean hasScreenId(long screenId) {
1059 SQLiteDatabase db = getWritableDatabase();
1060 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1061 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1062 if (c != null) {
1063 int count = c.getCount();
1064 c.close();
1065 return count > 0;
1066 } else {
1067 return false;
1068 }
1069 }
1070
1071 private int getMaxScreenRank() {
1072 SQLiteDatabase db = getWritableDatabase();
1073 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1074 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1075
1076 // get the result
1077 final int maxRankIndex = 0;
1078 int rank = -1;
1079 if (c != null && c.moveToNext()) {
1080 rank = c.getInt(maxRankIndex);
1081 }
1082 if (c != null) {
1083 c.close();
1084 }
1085
1086 return rank;
1087 }
1088
Adam Cohen091440a2015-03-18 14:16:05 -07001089 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001090 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001091 // TODO: Use multiple loaders with fall-back and transaction.
1092 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001093
1094 // Add the screens specified by the items above
1095 Collections.sort(screenIds);
1096 int rank = 0;
1097 ContentValues values = new ContentValues();
1098 for (Long id : screenIds) {
1099 values.clear();
1100 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1101 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1102 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1103 throw new RuntimeException("Failed initialize screen table"
1104 + "from default layout");
1105 }
1106 rank++;
1107 }
1108
1109 // Ensure that the max ids are initialized
1110 mMaxItemId = initializeMaxItemId(db);
1111 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001112
Adam Cohen71483f42014-05-15 14:04:01 -07001113 return count;
1114 }
1115
Adam Cohen091440a2015-03-18 14:16:05 -07001116 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001117 final ContentResolver resolver = mContext.getContentResolver();
1118 Cursor c = null;
1119 int count = 0;
1120 int curScreen = 0;
1121
1122 try {
1123 c = resolver.query(uri, null, null, null, "title ASC");
1124 } catch (Exception e) {
1125 // Ignore
1126 }
1127
Dan Sandlerd5024042014-01-09 15:01:33 -05001128 // We already have a favorites database in the old provider
1129 if (c != null) {
1130 try {
1131 if (c.getCount() > 0) {
1132 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1133 final int intentIndex
1134 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1135 final int titleIndex
1136 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1137 final int iconTypeIndex
1138 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1139 final int iconIndex
1140 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1141 final int iconPackageIndex
1142 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1143 final int iconResourceIndex
1144 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1145 final int containerIndex
1146 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1147 final int itemTypeIndex
1148 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1149 final int screenIndex
1150 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1151 final int cellXIndex
1152 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1153 final int cellYIndex
1154 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Kenny Guyed131872014-04-30 03:02:21 +01001155 final int profileIndex
1156 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001157
1158 int i = 0;
1159 int curX = 0;
1160 int curY = 0;
1161
1162 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001163 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1164 final int width = (int) profile.numColumns;
1165 final int height = (int) profile.numRows;
1166 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001167
1168 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1169
Adam Cohen72960972014-01-15 18:13:55 -08001170 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1171 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001172 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001173
1174 while (c.moveToNext()) {
1175 final int itemType = c.getInt(itemTypeIndex);
1176 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1177 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1178 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1179 continue;
1180 }
1181
1182 final int cellX = c.getInt(cellXIndex);
1183 final int cellY = c.getInt(cellYIndex);
1184 final int screen = c.getInt(screenIndex);
1185 int container = c.getInt(containerIndex);
1186 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001187
1188 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1189 UserHandleCompat userHandle;
1190 final long userSerialNumber;
1191 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1192 userSerialNumber = c.getInt(profileIndex);
1193 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1194 } else {
1195 // Default to the serial number of this user, for older
1196 // shortcuts.
1197 userHandle = UserHandleCompat.myUserHandle();
1198 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1199 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001200
1201 if (userHandle == null) {
Sunny Goyala1365452015-10-01 15:46:24 -07001202 Log.d(TAG, "skipping deleted user");
Sunny Goyal416541c2014-11-14 11:59:57 -08001203 continue;
1204 }
1205
Dan Sandlerd5024042014-01-09 15:01:33 -05001206 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001207
1208 final Intent intent;
1209 final ComponentName cn;
1210 try {
1211 intent = Intent.parseUri(intentStr, 0);
1212 } catch (URISyntaxException e) {
1213 // bogus intent?
Sunny Goyala1365452015-10-01 15:46:24 -07001214 Log.d(TAG, "skipping invalid intent uri");
Adam Cohen556f6132014-01-15 15:18:08 -08001215 continue;
1216 }
1217
1218 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001219 if (TextUtils.isEmpty(intentStr)) {
1220 // no intent? no icon
Sunny Goyala1365452015-10-01 15:46:24 -07001221 Log.d(TAG, "skipping empty intent");
Dan Sandlerd5024042014-01-09 15:01:33 -05001222 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001223 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001224 !LauncherModel.isValidPackageActivity(mContext, cn,
1225 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001226 // component no longer exists.
Sunny Goyala1365452015-10-01 15:46:24 -07001227 Log.d(TAG, "skipping item whose component no longer exists.");
Adam Cohen556f6132014-01-15 15:18:08 -08001228 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001229 } else if (container ==
1230 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1231 // Dedupe icons directly on the workspace
1232
Adam Cohen556f6132014-01-15 15:18:08 -08001233 // Canonicalize
1234 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001235 // does not, so we clear that out to keep them the same.
1236 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001237 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001238 int flags = intent.getFlags();
1239 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001240 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001241 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001242 if (seenIntents.contains(key)) {
Sunny Goyala1365452015-10-01 15:46:24 -07001243 Log.d(TAG, "skipping duplicate");
Dan Sandlerd5024042014-01-09 15:01:33 -05001244 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001245 } else {
1246 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001247 }
1248 }
1249 }
1250
1251 ContentValues values = new ContentValues(c.getColumnCount());
1252 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1253 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1254 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1255 values.put(LauncherSettings.Favorites.ICON_TYPE,
1256 c.getInt(iconTypeIndex));
1257 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1258 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1259 c.getString(iconPackageIndex));
1260 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1261 c.getString(iconResourceIndex));
1262 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1263 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
Kenny Guyed131872014-04-30 03:02:21 +01001264 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001265
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001266 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1267 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001268 }
1269
1270 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1271 // In a folder or in the hotseat, preserve position
1272 values.put(LauncherSettings.Favorites.SCREEN, screen);
1273 values.put(LauncherSettings.Favorites.CELLX, cellX);
1274 values.put(LauncherSettings.Favorites.CELLY, cellY);
1275 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001276 // For items contained directly on one of the workspace screen,
1277 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001278 }
1279
1280 values.put(LauncherSettings.Favorites.CONTAINER, container);
1281
Adam Cohen72960972014-01-15 18:13:55 -08001282 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1283 shortcuts.add(values);
1284 } else {
1285 folders.add(values);
1286 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001287 }
1288
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001289 // Now that we have all the hotseat icons, let's go through them left-right
1290 // and assign valid locations for them in the new hotseat
1291 final int N = hotseat.size();
1292 for (int idx=0; idx<N; idx++) {
1293 int hotseatX = hotseat.keyAt(idx);
1294 ContentValues values = hotseat.valueAt(idx);
1295
Adam Cohen2e6da152015-05-06 11:42:25 -07001296 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001297 // let's drop this in the next available hole in the hotseat
1298 while (++hotseatX < hotseatWidth) {
1299 if (hotseat.get(hotseatX) == null) {
1300 // found a spot! move it here
1301 values.put(LauncherSettings.Favorites.SCREEN,
1302 hotseatX);
1303 break;
1304 }
1305 }
1306 }
1307 if (hotseatX >= hotseatWidth) {
1308 // no room for you in the hotseat? it's off to the desktop with you
1309 values.put(LauncherSettings.Favorites.CONTAINER,
1310 Favorites.CONTAINER_DESKTOP);
1311 }
1312 }
1313
Adam Cohen72960972014-01-15 18:13:55 -08001314 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1315 // Folders first
1316 allItems.addAll(folders);
1317 // Then shortcuts
1318 allItems.addAll(shortcuts);
1319
1320 // Layout all the folders
1321 for (ContentValues values: allItems) {
1322 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1323 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1324 // Hotseat items and folder items have already had their
1325 // location information set. Nothing to be done here.
1326 continue;
1327 }
1328 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1329 values.put(LauncherSettings.Favorites.CELLX, curX);
1330 values.put(LauncherSettings.Favorites.CELLY, curY);
1331 curX = (curX + 1) % width;
1332 if (curX == 0) {
1333 curY = (curY + 1);
1334 }
1335 // Leave the last row of icons blank on every screen
1336 if (curY == height - 1) {
1337 curScreen = (int) generateNewScreenId();
1338 curY = 0;
1339 }
1340 }
1341
1342 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001343 db.beginTransaction();
1344 try {
Adam Cohen72960972014-01-15 18:13:55 -08001345 for (ContentValues row: allItems) {
1346 if (row == null) continue;
1347 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001348 < 0) {
1349 return;
1350 } else {
1351 count++;
1352 }
1353 }
1354 db.setTransactionSuccessful();
1355 } finally {
1356 db.endTransaction();
1357 }
1358 }
1359
1360 db.beginTransaction();
1361 try {
1362 for (i=0; i<=curScreen; i++) {
1363 final ContentValues values = new ContentValues();
1364 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1365 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1366 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1367 < 0) {
1368 return;
1369 }
1370 }
1371 db.setTransactionSuccessful();
1372 } finally {
1373 db.endTransaction();
1374 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001375
1376 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001377 }
1378 } finally {
1379 c.close();
1380 }
1381 }
1382
Sunny Goyala1365452015-10-01 15:46:24 -07001383 Log.d(TAG, "migrated " + count + " icons from Launcher2 into "
1384 + (curScreen+1) + " screens");
Dan Sandlerd5024042014-01-09 15:01:33 -05001385
1386 // ensure that new screens are created to hold these icons
1387 setFlagJustLoadedOldDb();
1388
1389 // Update max IDs; very important since we just grabbed IDs from another database
1390 mMaxItemId = initializeMaxItemId(db);
1391 mMaxScreenId = initializeMaxScreenId(db);
1392 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1393 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001394 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001395
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001396 /**
1397 * @return the max _id in the provided table.
1398 */
Adam Cohen091440a2015-03-18 14:16:05 -07001399 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001400 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1401 // get the result
1402 long id = -1;
1403 if (c != null && c.moveToNext()) {
1404 id = c.getLong(0);
1405 }
1406 if (c != null) {
1407 c.close();
1408 }
1409
1410 if (id == -1) {
1411 throw new RuntimeException("Error: could not query max id in " + table);
1412 }
1413
1414 return id;
1415 }
1416
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001417 static class SqlArguments {
1418 public final String table;
1419 public final String where;
1420 public final String[] args;
1421
1422 SqlArguments(Uri url, String where, String[] args) {
1423 if (url.getPathSegments().size() == 1) {
1424 this.table = url.getPathSegments().get(0);
1425 this.where = where;
1426 this.args = args;
1427 } else if (url.getPathSegments().size() != 2) {
1428 throw new IllegalArgumentException("Invalid URI: " + url);
1429 } else if (!TextUtils.isEmpty(where)) {
1430 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1431 } else {
1432 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001433 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001434 this.args = null;
1435 }
1436 }
1437
1438 SqlArguments(Uri url) {
1439 if (url.getPathSegments().size() == 1) {
1440 table = url.getPathSegments().get(0);
1441 where = null;
1442 args = null;
1443 } else {
1444 throw new IllegalArgumentException("Invalid URI: " + url);
1445 }
1446 }
1447 }
Adam Cohen72960972014-01-15 18:13:55 -08001448}