blob: f095a054e408a05ced8972ee13b813c74bf65011 [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;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070068 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080069 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
Sunny Goyal5c97f512015-05-19 16:03:28 -070071 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072
Sunny Goyale5bb7052015-07-27 14:36:07 -070073 public static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070074
Sunny Goyal18b640c2015-04-17 09:24:01 -070075 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
76 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080077 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070079 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
80
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 final Context context = getContext();
Sunny Goyal7bce5f72015-11-24 11:40:40 -080087 // The content provider exists for the entire duration of the launcher main process and
88 // is the first component to get created. Initializing application context here ensures
89 // that LauncherAppState always exists in the main process.
90 LauncherAppState.setApplicationContext(context.getApplicationContext());
Nilesh Agrawala258f812015-01-26 14:07:29 -080091 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040092 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080093 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040094 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095 return true;
96 }
97
Winson Chung0b560dd2014-01-21 13:00:26 -080098 public boolean wasNewDbCreated() {
99 return mOpenHelper.wasNewDbCreated();
100 }
101
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700102 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
103 mListener = listener;
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700104 mOpenHelper.mListener = mListener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700105 }
106
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107 @Override
108 public String getType(Uri uri) {
109 SqlArguments args = new SqlArguments(uri, null, null);
110 if (TextUtils.isEmpty(args.where)) {
111 return "vnd.android.cursor.dir/" + args.table;
112 } else {
113 return "vnd.android.cursor.item/" + args.table;
114 }
115 }
116
117 @Override
118 public Cursor query(Uri uri, String[] projection, String selection,
119 String[] selectionArgs, String sortOrder) {
120
121 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
122 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
123 qb.setTables(args.table);
124
Romain Guy73b979d2009-06-09 12:57:21 -0700125 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
127 result.setNotificationUri(getContext().getContentResolver(), uri);
128
129 return result;
130 }
131
Adam Cohen091440a2015-03-18 14:16:05 -0700132 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500134 if (values == null) {
135 throw new RuntimeException("Error: attempting to insert null values");
136 }
Adam Cohen71483f42014-05-15 14:04:01 -0700137 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 throw new RuntimeException("Error: attempting to add item without specifying an id");
139 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500140 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 return db.insert(table, nullColumnHack, values);
142 }
143
Sunny Goyald1064182015-08-13 12:08:30 -0700144 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700145 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700146 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
147 if (app != null) {
148 app.reloadWorkspace();
149 }
150 }
151 }
152
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800153 @Override
154 public Uri insert(Uri uri, ContentValues initialValues) {
155 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
Adam Cohena043fa82014-07-23 14:49:38 -0700189
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190 @Override
191 public int bulkInsert(Uri uri, ContentValues[] values) {
192 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 {
217 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
218 db.beginTransaction();
219 try {
220 ContentProviderResult[] result = super.applyBatch(operations);
221 db.setTransactionSuccessful();
Sunny Goyald1064182015-08-13 12:08:30 -0700222 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000223 return result;
224 } finally {
225 db.endTransaction();
226 }
227 }
228
229 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800230 public int delete(Uri uri, String selection, String[] selectionArgs) {
231 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
232
233 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
234 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700235 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236
Sunny Goyald1064182015-08-13 12:08:30 -0700237 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 return count;
239 }
240
241 @Override
242 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
243 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
244
Chris Wren1ada10d2013-09-13 18:01:38 -0400245 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800246 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
247 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700248 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800249
Sunny Goyald1064182015-08-13 12:08:30 -0700250 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800251 return count;
252 }
253
Sunny Goyal7779d622015-06-11 16:18:39 -0700254 @Override
255 public Bundle call(String method, String arg, Bundle extras) {
256 if (Binder.getCallingUid() != Process.myUid()) {
257 return null;
258 }
259
260 switch (method) {
261 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
262 Bundle result = new Bundle();
263 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Sunny Goyalf7258242015-10-19 16:59:07 -0700264 Utilities.getPrefs(getContext()).getBoolean(arg, extras.getBoolean(
265 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
Sunny Goyal7779d622015-06-11 16:18:39 -0700266 return result;
267 }
268 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
269 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
Sunny Goyalf7258242015-10-19 16:59:07 -0700270 Utilities.getPrefs(getContext()).edit().putBoolean(arg, value).apply();
Sunny Goyal7779d622015-06-11 16:18:39 -0700271 if (mListener != null) {
272 mListener.onSettingsChanged(arg, value);
273 }
274 Bundle result = new Bundle();
275 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
276 return result;
277 }
278 }
279 return null;
280 }
281
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700282 /**
283 * Deletes any empty folder from the DB.
284 * @return Ids of deleted folders.
285 */
286 public List<Long> deleteEmptyFolders() {
287 ArrayList<Long> folderIds = new ArrayList<Long>();
288 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
289 db.beginTransaction();
290 try {
291 // Select folders whose id do not match any container value.
292 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
293 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
294 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
295 LauncherSettings.Favorites.CONTAINER + " FROM "
296 + TABLE_FAVORITES + ")";
297 Cursor c = db.query(TABLE_FAVORITES,
298 new String[] {LauncherSettings.Favorites._ID},
299 selection, null, null, null, null);
300 while (c.moveToNext()) {
301 folderIds.add(c.getLong(0));
302 }
303 c.close();
304 if (folderIds.size() > 0) {
305 db.delete(TABLE_FAVORITES, Utilities.createDbSelectionQuery(
306 LauncherSettings.Favorites._ID, folderIds), null);
307 }
308 db.setTransactionSuccessful();
309 } catch (SQLException ex) {
310 Log.e(TAG, ex.getMessage(), ex);
311 folderIds.clear();
312 } finally {
313 db.endTransaction();
314 }
315 return folderIds;
316 }
317
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700318 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400319 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400320 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700321 if (mListener != null) {
322 mListener.onLauncherProviderChange();
323 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400324 }
325
Adam Cohen091440a2015-03-18 14:16:05 -0700326 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400327 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 }
329
Adam Cohendcd297f2013-06-18 13:13:40 -0700330 public long generateNewItemId() {
331 return mOpenHelper.generateNewItemId();
332 }
333
334 public long generateNewScreenId() {
335 return mOpenHelper.generateNewScreenId();
336 }
337
Brian Muramatsu5524b492012-10-02 16:55:54 -0700338 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700339 * Clears all the data for a fresh start.
340 */
341 synchronized public void createEmptyDB() {
342 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
343 }
344
Sunny Goyal33d44382014-10-16 09:24:19 -0700345 public void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700346 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700347 }
348
Sunny Goyal42de82f2014-09-26 22:09:29 -0700349 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700350 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700351 * 1) From the app restrictions
352 * 2) From a package provided by play store
353 * 3) From a partner configuration APK, already in the system image
354 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700355 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700356 synchronized public void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700357 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700358
Winson Chungc763c4e2013-07-19 13:49:06 -0700359 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500360 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200361
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700362 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
363 if (loader == null) {
364 loader = AutoInstallsLayout.get(getContext(),
365 mOpenHelper.mAppWidgetHost, mOpenHelper);
366 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700367 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700368 final Partner partner = Partner.get(getContext().getPackageManager());
369 if (partner != null && partner.hasDefaultLayout()) {
370 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700371 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700372 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700373 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700374 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
375 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700376 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700377 }
378 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700379
Sunny Goyal9d219682014-10-23 14:21:02 -0700380 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700381 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700382 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700383 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800384
385 // There might be some partially restored DB items, due to buggy restore logic in
386 // previous versions of launcher.
387 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700388 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700389 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
390 && usingExternallyProvidedLayout) {
391 // Unable to load external layout. Cleanup and load the internal layout.
392 createEmptyDB();
393 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
394 getDefaultLayoutParser());
395 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700396 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700397 }
398 }
399
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700400 /**
401 * Creates workspace loader from an XML resource listed in the app restrictions.
402 *
403 * @return the loader if the restrictions are set and the resource exists; null otherwise.
404 */
405 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
406 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
407 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700408 if (!Utilities.ATLEAST_JB_MR2) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700409 return null;
410 }
411
412 Context ctx = getContext();
413 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
414 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700415 if (bundle == null) {
416 return null;
417 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700418
Sunny Goyal35ca8732015-04-06 10:45:31 -0700419 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700420 if (packageName != null) {
421 try {
422 Resources targetResources = ctx.getPackageManager()
423 .getResourcesForApplication(packageName);
424 return AutoInstallsLayout.get(ctx, packageName, targetResources,
425 mOpenHelper.mAppWidgetHost, mOpenHelper);
426 } catch (NameNotFoundException e) {
427 Log.e(TAG, "Target package for restricted profile not found", e);
428 return null;
429 }
430 }
431 return null;
432 }
433
Sunny Goyal9d219682014-10-23 14:21:02 -0700434 private DefaultLayoutParser getDefaultLayoutParser() {
435 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700436 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700437 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
438 mOpenHelper, getContext().getResources(), defaultLayout);
439 }
440
Dan Sandlerd5024042014-01-09 15:01:33 -0500441 public void migrateLauncher2Shortcuts() {
442 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400443 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500444 }
445
Sunny Goyal08f72612015-01-05 13:41:43 -0800446 public void updateFolderItemsRank() {
447 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
448 }
449
Sunny Goyal5c97f512015-05-19 16:03:28 -0700450 public void convertShortcutsToLauncherActivities() {
451 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
452 }
453
454
Dan Sandlerd5024042014-01-09 15:01:33 -0500455 public void deleteDatabase() {
456 // Are you sure? (y/n)
457 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500458 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500459 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500460 if (dbFile.exists()) {
461 SQLiteDatabase.deleteDatabase(dbFile);
462 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500463 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700464 mOpenHelper.mListener = mListener;
Dan Sandlerd5024042014-01-09 15:01:33 -0500465 }
466
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700469 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700470 private long mMaxItemId = -1;
471 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472
Winson Chung0b560dd2014-01-21 13:00:26 -0800473 private boolean mNewDbCreated = false;
474
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700475 @Thunk LauncherProviderChangeListener mListener;
476
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100478 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800479 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700480 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700481
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700482 // Table creation sometimes fails silently, which leads to a crash loop.
483 // This way, we will try to create a table every time after crash, so the device
484 // would eventually be able to recover.
485 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
486 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
487 // This operation is a no-op if the table already exists.
488 addFavoritesTable(getWritableDatabase(), true);
489 addWorkspacesTable(getWritableDatabase(), true);
490 }
491
Winson Chung3d503fb2011-07-13 17:25:49 -0700492 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
493 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700494 if (mMaxItemId == -1) {
495 mMaxItemId = initializeMaxItemId(getWritableDatabase());
496 }
497 if (mMaxScreenId == -1) {
498 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700499 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800500 }
501
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700502 private boolean tableExists(String tableName) {
503 Cursor c = getReadableDatabase().query(
504 true, "sqlite_master", new String[] {"tbl_name"},
505 "tbl_name = ?", new String[] {tableName},
506 null, null, null, null, null);
507 try {
508 return c.getCount() > 0;
509 } finally {
510 c.close();
511 }
512 }
513
Winson Chung0b560dd2014-01-21 13:00:26 -0800514 public boolean wasNewDbCreated() {
515 return mNewDbCreated;
516 }
517
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 @Override
519 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800520 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700521
Adam Cohendcd297f2013-06-18 13:13:40 -0700522 mMaxItemId = 1;
523 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800524 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700525
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700526 addFavoritesTable(db, false);
527 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800528
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700529 // Database was just created, so wipe any previous widgets
530 if (mAppWidgetHost != null) {
531 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700532
533 /**
534 * Send notification that we've deleted the {@link AppWidgetHost},
535 * probably as part of the initial database creation. The receiver may
536 * want to re-call {@link AppWidgetHost#startListening()} to ensure
537 * callbacks are correctly set.
538 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700539 new MainThreadExecutor().execute(new Runnable() {
540
541 @Override
542 public void run() {
543 if (mListener != null) {
544 mListener.onAppWidgetHostReset();
545 }
546 }
547 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700549
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800550 // Fresh and clean launcher DB.
551 mMaxItemId = initializeMaxItemId(db);
552 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700553
554 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700555 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800556 }
557
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700558 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
559 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
560 long userSerialNumber = userManager.getSerialNumberForUser(
561 UserHandleCompat.myUserHandle());
562 String ifNotExists = optional ? " IF NOT EXISTS " : "";
563
564 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
565 "_id INTEGER PRIMARY KEY," +
566 "title TEXT," +
567 "intent TEXT," +
568 "container INTEGER," +
569 "screen INTEGER," +
570 "cellX INTEGER," +
571 "cellY INTEGER," +
572 "spanX INTEGER," +
573 "spanY INTEGER," +
574 "itemType INTEGER," +
575 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
576 "isShortcut INTEGER," +
577 "iconType INTEGER," +
578 "iconPackage TEXT," +
579 "iconResource TEXT," +
580 "icon BLOB," +
581 "uri TEXT," +
582 "displayMode INTEGER," +
583 "appWidgetProvider TEXT," +
584 "modified INTEGER NOT NULL DEFAULT 0," +
585 "restored INTEGER NOT NULL DEFAULT 0," +
586 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
587 "rank INTEGER NOT NULL DEFAULT 0," +
588 "options INTEGER NOT NULL DEFAULT 0" +
589 ");");
590 }
591
592 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
593 String ifNotExists = optional ? " IF NOT EXISTS " : "";
594 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800595 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400596 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
597 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700598 ");");
599 }
600
Adam Cohen119285e2014-04-02 16:59:08 -0700601 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700602 // Delete items directly on the workspace who's screen id doesn't exist
603 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
604 // AND container = -100"
605 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
606 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700607 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700608 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
609 " AND " +
610 LauncherSettings.Favorites.CONTAINER + " = " +
611 LauncherSettings.Favorites.CONTAINER_DESKTOP;
612 db.execSQL(removeOrphanedDesktopItems);
613
614 // Delete items contained in folders which no longer exist (after above statement)
615 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
616 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
617 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
618 " WHERE " +
619 LauncherSettings.Favorites.CONTAINER + " <> " +
620 LauncherSettings.Favorites.CONTAINER_DESKTOP +
621 " AND "
622 + LauncherSettings.Favorites.CONTAINER + " <> " +
623 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
624 " AND "
625 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
626 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
627 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
628 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
629 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700630 }
631
Winson Chungc763c4e2013-07-19 13:49:06 -0700632 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700633 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700634 }
635
Winson Chungc763c4e2013-07-19 13:49:06 -0700636 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700637 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700638 }
639
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 @Override
641 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700642 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800643 switch (oldVersion) {
644 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800645 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800646 case 12: {
647 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
648 // to persist workspace screens and their relative order.
649 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700650 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800651 }
652 case 13: {
653 db.beginTransaction();
654 try {
655 // Insert new column for holding widget provider name
656 db.execSQL("ALTER TABLE favorites " +
657 "ADD COLUMN appWidgetProvider TEXT;");
658 db.setTransactionSuccessful();
659 } catch (SQLException ex) {
660 Log.e(TAG, ex.getMessage(), ex);
661 // Old version remains, which means we wipe old data
662 break;
663 } finally {
664 db.endTransaction();
665 }
666 }
667 case 14: {
668 db.beginTransaction();
669 try {
670 // Insert new column for holding update timestamp
671 db.execSQL("ALTER TABLE favorites " +
672 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
673 db.execSQL("ALTER TABLE workspaceScreens " +
674 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
675 db.setTransactionSuccessful();
676 } catch (SQLException ex) {
677 Log.e(TAG, ex.getMessage(), ex);
678 // Old version remains, which means we wipe old data
679 break;
680 } finally {
681 db.endTransaction();
682 }
683 }
684 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700685 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800686 // Old version remains, which means we wipe old data
687 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800688 }
689 }
690 case 16: {
691 // We use the db version upgrade here to identify users who may not have seen
692 // clings yet (because they weren't available), but for whom the clings are now
693 // available (tablet users). Because one of the possible cling flows (migration)
694 // is very destructive (wipes out workspaces), we want to prevent this from showing
695 // until clear data. We do so by marking that the clings have been shown.
696 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
697 }
698 case 17: {
699 // No-op
700 }
701 case 18: {
702 // Due to a data loss bug, some users may have items associated with screen ids
703 // which no longer exist. Since this can cause other problems, and since the user
704 // will never see these items anyway, we use database upgrade as an opportunity to
705 // clean things up.
706 removeOrphanedItems(db);
707 }
708 case 19: {
709 // Add userId column
710 if (!addProfileColumn(db)) {
711 // Old version remains, which means we wipe old data
712 break;
713 }
714 }
715 case 20:
716 if (!updateFolderItemsRank(db, true)) {
717 break;
718 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800719 case 21:
720 // Recreate workspace table with screen id a primary key
721 if (!recreateWorkspaceTable(db)) {
722 break;
723 }
724 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700725 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
726 // Old version remains, which means we wipe old data
727 break;
728 }
729 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700730 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700731 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700732 case 24:
733 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700734 case 25:
735 convertShortcutsToLauncherActivities(db);
736 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 // DB Upgraded successfully
738 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400739 }
740 }
741
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 // DB was not upgraded
743 Log.w(TAG, "Destroying all old data.");
744 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800745 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800746
Adam Cohen9b1d0622014-05-21 19:01:57 -0700747 @Override
748 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
749 // This shouldn't happen -- throw our hands up in the air and start over.
750 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
751 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700752 createEmptyDB(db);
753 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700754
Sunny Goyal42de82f2014-09-26 22:09:29 -0700755 /**
756 * Clears all the data for a fresh start.
757 */
758 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700759 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
760 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
761 onCreate(db);
762 }
763
Sunny Goyald2f38192015-02-25 10:46:34 -0800764 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700765 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
766 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
767 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700768 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700769 db.beginTransaction();
770 Cursor c = null;
771 SQLiteStatement updateStmt = null;
772
773 try {
774 // Only consider the primary user as other users can't have a shortcut.
775 long userSerial = UserManagerCompat.getInstance(mContext)
776 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
777 c = db.query(TABLE_FAVORITES, new String[] {
778 Favorites._ID,
779 Favorites.INTENT,
780 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
781 null, null, null, null);
782
783 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
784 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
785
786 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
787 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
788
789 while (c.moveToNext()) {
790 String intentDescription = c.getString(intentIndex);
791 Intent intent;
792 try {
793 intent = Intent.parseUri(intentDescription, 0);
794 } catch (URISyntaxException e) {
795 Log.e(TAG, "Unable to parse intent", e);
796 continue;
797 }
798
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700799 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700800 continue;
801 }
802
803 long id = c.getLong(idIndex);
804 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700805 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700806 }
807 db.setTransactionSuccessful();
808 } catch (SQLException ex) {
809 Log.w(TAG, "Error deduping shortcuts", ex);
810 } finally {
811 db.endTransaction();
812 if (c != null) {
813 c.close();
814 }
815 if (updateStmt != null) {
816 updateStmt.close();
817 }
818 }
819 }
820
821 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800822 * Recreates workspace table and migrates data to the new table.
823 */
824 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
825 db.beginTransaction();
826 try {
827 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
828 new String[] {LauncherSettings.WorkspaceScreens._ID},
829 null, null, null, null,
830 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
831 ArrayList<Long> sortedIDs = new ArrayList<Long>();
832 long maxId = 0;
833 try {
834 while (c.moveToNext()) {
835 Long id = c.getLong(0);
836 if (!sortedIDs.contains(id)) {
837 sortedIDs.add(id);
838 maxId = Math.max(maxId, id);
839 }
840 }
841 } finally {
842 c.close();
843 }
844
845 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700846 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800847
848 // Add all screen ids back
849 int total = sortedIDs.size();
850 for (int i = 0; i < total; i++) {
851 ContentValues values = new ContentValues();
852 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
853 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
854 addModifiedTime(values);
855 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
856 }
857 db.setTransactionSuccessful();
858 mMaxScreenId = maxId;
859 } catch (SQLException ex) {
860 // Old version remains, which means we wipe old data
861 Log.e(TAG, ex.getMessage(), ex);
862 return false;
863 } finally {
864 db.endTransaction();
865 }
866 return true;
867 }
868
Adam Cohen091440a2015-03-18 14:16:05 -0700869 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800870 db.beginTransaction();
871 try {
872 if (addRankColumn) {
873 // Insert new column for holding rank
874 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
875 }
876
877 // Get a map for folder ID to folder width
878 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
879 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
880 + " GROUP BY container;",
881 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
882
883 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800884 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
885 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800886 new Object[] {c.getLong(1) + 1, c.getLong(0)});
887 }
888
889 c.close();
890 db.setTransactionSuccessful();
891 } catch (SQLException ex) {
892 // Old version remains, which means we wipe old data
893 Log.e(TAG, ex.getMessage(), ex);
894 return false;
895 } finally {
896 db.endTransaction();
897 }
898 return true;
899 }
900
Kenny Guyed131872014-04-30 03:02:21 +0100901 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700902 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
903 // Default to the serial number of this user, for older
904 // shortcuts.
905 long userSerialNumber = userManager.getSerialNumberForUser(
906 UserHandleCompat.myUserHandle());
907 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
908 }
909
910 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100911 db.beginTransaction();
912 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700913 db.execSQL("ALTER TABLE favorites ADD COLUMN "
914 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100915 db.setTransactionSuccessful();
916 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100917 Log.e(TAG, ex.getMessage(), ex);
918 return false;
919 } finally {
920 db.endTransaction();
921 }
922 return true;
923 }
924
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700925 // Generates a new ID to use for an object in your database. This method should be only
926 // called from the main UI thread. As an exception, we do call it when we call the
927 // constructor from the worker thread; however, this doesn't extend until after the
928 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
929 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700930 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700931 public long generateNewItemId() {
932 if (mMaxItemId < 0) {
933 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700934 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700935 mMaxItemId += 1;
936 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700937 }
938
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700939 @Override
940 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
941 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
942 }
943
Chris Wren5dee7af2013-12-20 17:22:11 -0500944 public void checkId(String table, ContentValues values) {
945 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
946 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
947 mMaxScreenId = Math.max(id, mMaxScreenId);
948 } else {
949 mMaxItemId = Math.max(id, mMaxItemId);
950 }
951 }
952
Adam Cohendcd297f2013-06-18 13:13:40 -0700953 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800954 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700955 }
956
957 // Generates a new ID to use for an workspace screen in your database. This method
958 // should be only called from the main UI thread. As an exception, we do call it when we
959 // call the constructor from the worker thread; however, this doesn't extend until after the
960 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
961 // after that point
962 public long generateNewScreenId() {
963 if (mMaxScreenId < 0) {
964 throw new RuntimeException("Error: max screen id was not initialized");
965 }
966 mMaxScreenId += 1;
967 return mMaxScreenId;
968 }
969
Adam Cohendcd297f2013-06-18 13:13:40 -0700970 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800971 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800972 }
973
Adam Cohen091440a2015-03-18 14:16:05 -0700974 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700975 // 1. Ensure that externally added items have a valid item id
976 long id = generateNewItemId();
977 values.put(LauncherSettings.Favorites._ID, id);
978
979 // 2. In the case of an app widget, and if no app widget id is specified, we
980 // attempt allocate and bind the widget.
981 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
982 if (itemType != null &&
983 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
984 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
985
986 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
987 ComponentName cn = ComponentName.unflattenFromString(
988 values.getAsString(Favorites.APPWIDGET_PROVIDER));
989
990 if (cn != null) {
991 try {
992 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700993 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700994 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700995 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700996 }
997 } catch (RuntimeException e) {
998 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700999 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001000 }
Adam Coheneb1ac422014-10-14 08:55:28 -07001001 } else {
1002 return false;
Adam Cohena043fa82014-07-23 14:49:38 -07001003 }
1004 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001005
1006 // Add screen id if not present
1007 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1008 if (!addScreenIdIfNecessary(screenId)) {
1009 return false;
1010 }
Adam Cohena043fa82014-07-23 14:49:38 -07001011 return true;
1012 }
1013
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001014 // Returns true of screen id exists, or if successfully added
1015 private boolean addScreenIdIfNecessary(long screenId) {
1016 if (!hasScreenId(screenId)) {
1017 int rank = getMaxScreenRank() + 1;
1018
1019 ContentValues v = new ContentValues();
1020 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1021 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1022 if (dbInsertAndCheck(this, getWritableDatabase(),
1023 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1024 return false;
1025 }
1026 }
1027 return true;
1028 }
1029
1030 private boolean hasScreenId(long screenId) {
1031 SQLiteDatabase db = getWritableDatabase();
1032 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1033 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1034 if (c != null) {
1035 int count = c.getCount();
1036 c.close();
1037 return count > 0;
1038 } else {
1039 return false;
1040 }
1041 }
1042
1043 private int getMaxScreenRank() {
1044 SQLiteDatabase db = getWritableDatabase();
1045 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1046 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1047
1048 // get the result
1049 final int maxRankIndex = 0;
1050 int rank = -1;
1051 if (c != null && c.moveToNext()) {
1052 rank = c.getInt(maxRankIndex);
1053 }
1054 if (c != null) {
1055 c.close();
1056 }
1057
1058 return rank;
1059 }
1060
Adam Cohen091440a2015-03-18 14:16:05 -07001061 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001062 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001063 // TODO: Use multiple loaders with fall-back and transaction.
1064 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001065
1066 // Add the screens specified by the items above
1067 Collections.sort(screenIds);
1068 int rank = 0;
1069 ContentValues values = new ContentValues();
1070 for (Long id : screenIds) {
1071 values.clear();
1072 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1073 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1074 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1075 throw new RuntimeException("Failed initialize screen table"
1076 + "from default layout");
1077 }
1078 rank++;
1079 }
1080
1081 // Ensure that the max ids are initialized
1082 mMaxItemId = initializeMaxItemId(db);
1083 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001084
Adam Cohen71483f42014-05-15 14:04:01 -07001085 return count;
1086 }
1087
Adam Cohen091440a2015-03-18 14:16:05 -07001088 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001089 final ContentResolver resolver = mContext.getContentResolver();
1090 Cursor c = null;
1091 int count = 0;
1092 int curScreen = 0;
1093
1094 try {
1095 c = resolver.query(uri, null, null, null, "title ASC");
1096 } catch (Exception e) {
1097 // Ignore
1098 }
1099
Dan Sandlerd5024042014-01-09 15:01:33 -05001100 // We already have a favorites database in the old provider
1101 if (c != null) {
1102 try {
1103 if (c.getCount() > 0) {
1104 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1105 final int intentIndex
1106 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1107 final int titleIndex
1108 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1109 final int iconTypeIndex
1110 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1111 final int iconIndex
1112 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1113 final int iconPackageIndex
1114 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1115 final int iconResourceIndex
1116 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1117 final int containerIndex
1118 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1119 final int itemTypeIndex
1120 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1121 final int screenIndex
1122 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1123 final int cellXIndex
1124 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1125 final int cellYIndex
1126 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1127 final int uriIndex
1128 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1129 final int displayModeIndex
1130 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001131 final int profileIndex
1132 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001133
1134 int i = 0;
1135 int curX = 0;
1136 int curY = 0;
1137
1138 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001139 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1140 final int width = (int) profile.numColumns;
1141 final int height = (int) profile.numRows;
1142 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001143
1144 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1145
Adam Cohen72960972014-01-15 18:13:55 -08001146 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1147 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001148 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001149
1150 while (c.moveToNext()) {
1151 final int itemType = c.getInt(itemTypeIndex);
1152 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1153 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1154 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1155 continue;
1156 }
1157
1158 final int cellX = c.getInt(cellXIndex);
1159 final int cellY = c.getInt(cellYIndex);
1160 final int screen = c.getInt(screenIndex);
1161 int container = c.getInt(containerIndex);
1162 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001163
1164 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1165 UserHandleCompat userHandle;
1166 final long userSerialNumber;
1167 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1168 userSerialNumber = c.getInt(profileIndex);
1169 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1170 } else {
1171 // Default to the serial number of this user, for older
1172 // shortcuts.
1173 userHandle = UserHandleCompat.myUserHandle();
1174 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1175 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001176
1177 if (userHandle == null) {
1178 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1179 continue;
1180 }
1181
Dan Sandlerd5024042014-01-09 15:01:33 -05001182 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001183 + c.getString(titleIndex) + "\" ("
1184 + cellX + "," + cellY + "@"
1185 + LauncherSettings.Favorites.containerToString(container)
1186 + "/" + screen
1187 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001188
1189 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001190
1191 final Intent intent;
1192 final ComponentName cn;
1193 try {
1194 intent = Intent.parseUri(intentStr, 0);
1195 } catch (URISyntaxException e) {
1196 // bogus intent?
1197 Launcher.addDumpLog(TAG,
1198 "skipping invalid intent uri", true);
1199 continue;
1200 }
1201
1202 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001203 if (TextUtils.isEmpty(intentStr)) {
1204 // no intent? no icon
1205 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1206 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001207 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001208 !LauncherModel.isValidPackageActivity(mContext, cn,
1209 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001210 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001211 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001212 "no longer exists.", true);
1213 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001214 } else if (container ==
1215 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1216 // Dedupe icons directly on the workspace
1217
Adam Cohen556f6132014-01-15 15:18:08 -08001218 // Canonicalize
1219 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001220 // does not, so we clear that out to keep them the same.
1221 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001222 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001223 int flags = intent.getFlags();
1224 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001225 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001226 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001227 if (seenIntents.contains(key)) {
1228 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001229 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001230 } else {
1231 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001232 }
1233 }
1234 }
1235
1236 ContentValues values = new ContentValues(c.getColumnCount());
1237 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1238 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1239 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1240 values.put(LauncherSettings.Favorites.ICON_TYPE,
1241 c.getInt(iconTypeIndex));
1242 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1243 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1244 c.getString(iconPackageIndex));
1245 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1246 c.getString(iconResourceIndex));
1247 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1248 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1249 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1250 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1251 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001252 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001253
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001254 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1255 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001256 }
1257
1258 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1259 // In a folder or in the hotseat, preserve position
1260 values.put(LauncherSettings.Favorites.SCREEN, screen);
1261 values.put(LauncherSettings.Favorites.CELLX, cellX);
1262 values.put(LauncherSettings.Favorites.CELLY, cellY);
1263 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001264 // For items contained directly on one of the workspace screen,
1265 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001266 }
1267
1268 values.put(LauncherSettings.Favorites.CONTAINER, container);
1269
Adam Cohen72960972014-01-15 18:13:55 -08001270 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1271 shortcuts.add(values);
1272 } else {
1273 folders.add(values);
1274 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001275 }
1276
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001277 // Now that we have all the hotseat icons, let's go through them left-right
1278 // and assign valid locations for them in the new hotseat
1279 final int N = hotseat.size();
1280 for (int idx=0; idx<N; idx++) {
1281 int hotseatX = hotseat.keyAt(idx);
1282 ContentValues values = hotseat.valueAt(idx);
1283
Adam Cohen2e6da152015-05-06 11:42:25 -07001284 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001285 // let's drop this in the next available hole in the hotseat
1286 while (++hotseatX < hotseatWidth) {
1287 if (hotseat.get(hotseatX) == null) {
1288 // found a spot! move it here
1289 values.put(LauncherSettings.Favorites.SCREEN,
1290 hotseatX);
1291 break;
1292 }
1293 }
1294 }
1295 if (hotseatX >= hotseatWidth) {
1296 // no room for you in the hotseat? it's off to the desktop with you
1297 values.put(LauncherSettings.Favorites.CONTAINER,
1298 Favorites.CONTAINER_DESKTOP);
1299 }
1300 }
1301
Adam Cohen72960972014-01-15 18:13:55 -08001302 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1303 // Folders first
1304 allItems.addAll(folders);
1305 // Then shortcuts
1306 allItems.addAll(shortcuts);
1307
1308 // Layout all the folders
1309 for (ContentValues values: allItems) {
1310 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1311 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1312 // Hotseat items and folder items have already had their
1313 // location information set. Nothing to be done here.
1314 continue;
1315 }
1316 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1317 values.put(LauncherSettings.Favorites.CELLX, curX);
1318 values.put(LauncherSettings.Favorites.CELLY, curY);
1319 curX = (curX + 1) % width;
1320 if (curX == 0) {
1321 curY = (curY + 1);
1322 }
1323 // Leave the last row of icons blank on every screen
1324 if (curY == height - 1) {
1325 curScreen = (int) generateNewScreenId();
1326 curY = 0;
1327 }
1328 }
1329
1330 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001331 db.beginTransaction();
1332 try {
Adam Cohen72960972014-01-15 18:13:55 -08001333 for (ContentValues row: allItems) {
1334 if (row == null) continue;
1335 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001336 < 0) {
1337 return;
1338 } else {
1339 count++;
1340 }
1341 }
1342 db.setTransactionSuccessful();
1343 } finally {
1344 db.endTransaction();
1345 }
1346 }
1347
1348 db.beginTransaction();
1349 try {
1350 for (i=0; i<=curScreen; i++) {
1351 final ContentValues values = new ContentValues();
1352 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1353 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1354 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1355 < 0) {
1356 return;
1357 }
1358 }
1359 db.setTransactionSuccessful();
1360 } finally {
1361 db.endTransaction();
1362 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001363
1364 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001365 }
1366 } finally {
1367 c.close();
1368 }
1369 }
1370
1371 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1372 + (curScreen+1) + " screens", true);
1373
1374 // ensure that new screens are created to hold these icons
1375 setFlagJustLoadedOldDb();
1376
1377 // Update max IDs; very important since we just grabbed IDs from another database
1378 mMaxItemId = initializeMaxItemId(db);
1379 mMaxScreenId = initializeMaxScreenId(db);
1380 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1381 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001382 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001383
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001384 /**
1385 * @return the max _id in the provided table.
1386 */
Adam Cohen091440a2015-03-18 14:16:05 -07001387 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001388 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1389 // get the result
1390 long id = -1;
1391 if (c != null && c.moveToNext()) {
1392 id = c.getLong(0);
1393 }
1394 if (c != null) {
1395 c.close();
1396 }
1397
1398 if (id == -1) {
1399 throw new RuntimeException("Error: could not query max id in " + table);
1400 }
1401
1402 return id;
1403 }
1404
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001405 static class SqlArguments {
1406 public final String table;
1407 public final String where;
1408 public final String[] args;
1409
1410 SqlArguments(Uri url, String where, String[] args) {
1411 if (url.getPathSegments().size() == 1) {
1412 this.table = url.getPathSegments().get(0);
1413 this.where = where;
1414 this.args = args;
1415 } else if (url.getPathSegments().size() != 2) {
1416 throw new IllegalArgumentException("Invalid URI: " + url);
1417 } else if (!TextUtils.isEmpty(where)) {
1418 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1419 } else {
1420 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001421 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001422 this.args = null;
1423 }
1424 }
1425
1426 SqlArguments(Uri url) {
1427 if (url.getPathSegments().size() == 1) {
1428 table = url.getPathSegments().get(0);
1429 where = null;
1430 args = null;
1431 } else {
1432 throw new IllegalArgumentException("Invalid URI: " + url);
1433 }
1434 }
1435 }
Adam Cohen72960972014-01-15 18:13:55 -08001436}