blob: 1390e67ad07671aaaf5851973171e94b0b79b697 [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)
Sunny Goyal33f90e72015-11-30 10:59:35 -0800457 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Dan Sandlerd5024042014-01-09 15:01:33 -0500458 }
459
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700460 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800461 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700462 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700463 private long mMaxItemId = -1;
464 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800465
Winson Chung0b560dd2014-01-21 13:00:26 -0800466 private boolean mNewDbCreated = false;
467
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700468 @Thunk LauncherProviderChangeListener mListener;
469
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800470 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100471 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700473 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700474
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700475 // Table creation sometimes fails silently, which leads to a crash loop.
476 // This way, we will try to create a table every time after crash, so the device
477 // would eventually be able to recover.
478 if (!tableExists(TABLE_FAVORITES) || !tableExists(TABLE_WORKSPACE_SCREENS)) {
479 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
480 // This operation is a no-op if the table already exists.
481 addFavoritesTable(getWritableDatabase(), true);
482 addWorkspacesTable(getWritableDatabase(), true);
483 }
484
Winson Chung3d503fb2011-07-13 17:25:49 -0700485 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
486 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700487 if (mMaxItemId == -1) {
488 mMaxItemId = initializeMaxItemId(getWritableDatabase());
489 }
490 if (mMaxScreenId == -1) {
491 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700492 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800493 }
494
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700495 private boolean tableExists(String tableName) {
496 Cursor c = getReadableDatabase().query(
497 true, "sqlite_master", new String[] {"tbl_name"},
498 "tbl_name = ?", new String[] {tableName},
499 null, null, null, null, null);
500 try {
501 return c.getCount() > 0;
502 } finally {
503 c.close();
504 }
505 }
506
Winson Chung0b560dd2014-01-21 13:00:26 -0800507 public boolean wasNewDbCreated() {
508 return mNewDbCreated;
509 }
510
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800511 @Override
512 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800513 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700514
Adam Cohendcd297f2013-06-18 13:13:40 -0700515 mMaxItemId = 1;
516 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800517 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700518
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700519 addFavoritesTable(db, false);
520 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800521
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700522 // Database was just created, so wipe any previous widgets
523 if (mAppWidgetHost != null) {
524 mAppWidgetHost.deleteHost();
Sunny Goyal383c5072015-06-12 21:18:53 -0700525
526 /**
527 * Send notification that we've deleted the {@link AppWidgetHost},
528 * probably as part of the initial database creation. The receiver may
529 * want to re-call {@link AppWidgetHost#startListening()} to ensure
530 * callbacks are correctly set.
531 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700532 new MainThreadExecutor().execute(new Runnable() {
533
534 @Override
535 public void run() {
536 if (mListener != null) {
537 mListener.onAppWidgetHostReset();
538 }
539 }
540 });
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800541 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700542
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800543 // Fresh and clean launcher DB.
544 mMaxItemId = initializeMaxItemId(db);
545 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700546
547 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal383c5072015-06-12 21:18:53 -0700548 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandleCompat>emptyList(), mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549 }
550
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700551 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
552 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
553 long userSerialNumber = userManager.getSerialNumberForUser(
554 UserHandleCompat.myUserHandle());
555 String ifNotExists = optional ? " IF NOT EXISTS " : "";
556
557 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_FAVORITES + " (" +
558 "_id INTEGER PRIMARY KEY," +
559 "title TEXT," +
560 "intent TEXT," +
561 "container INTEGER," +
562 "screen INTEGER," +
563 "cellX INTEGER," +
564 "cellY INTEGER," +
565 "spanX INTEGER," +
566 "spanY INTEGER," +
567 "itemType INTEGER," +
568 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
569 "isShortcut INTEGER," +
570 "iconType INTEGER," +
571 "iconPackage TEXT," +
572 "iconResource TEXT," +
573 "icon BLOB," +
574 "uri TEXT," +
575 "displayMode INTEGER," +
576 "appWidgetProvider TEXT," +
577 "modified INTEGER NOT NULL DEFAULT 0," +
578 "restored INTEGER NOT NULL DEFAULT 0," +
579 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
580 "rank INTEGER NOT NULL DEFAULT 0," +
581 "options INTEGER NOT NULL DEFAULT 0" +
582 ");");
583 }
584
585 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
586 String ifNotExists = optional ? " IF NOT EXISTS " : "";
587 db.execSQL("CREATE TABLE " + ifNotExists + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800588 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400589 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
590 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 ");");
592 }
593
Adam Cohen119285e2014-04-02 16:59:08 -0700594 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700595 // Delete items directly on the workspace who's screen id doesn't exist
596 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
597 // AND container = -100"
598 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
599 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700600 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700601 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
602 " AND " +
603 LauncherSettings.Favorites.CONTAINER + " = " +
604 LauncherSettings.Favorites.CONTAINER_DESKTOP;
605 db.execSQL(removeOrphanedDesktopItems);
606
607 // Delete items contained in folders which no longer exist (after above statement)
608 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
609 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
610 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
611 " WHERE " +
612 LauncherSettings.Favorites.CONTAINER + " <> " +
613 LauncherSettings.Favorites.CONTAINER_DESKTOP +
614 " AND "
615 + LauncherSettings.Favorites.CONTAINER + " <> " +
616 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
617 " AND "
618 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
619 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
620 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
621 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
622 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700623 }
624
Winson Chungc763c4e2013-07-19 13:49:06 -0700625 private void setFlagJustLoadedOldDb() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700626 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700627 }
628
Winson Chungc763c4e2013-07-19 13:49:06 -0700629 private void setFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700630 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700631 }
632
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 @Override
634 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700635 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800636 switch (oldVersion) {
637 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800638 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800639 case 12: {
640 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
641 // to persist workspace screens and their relative order.
642 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800644 }
645 case 13: {
646 db.beginTransaction();
647 try {
648 // Insert new column for holding widget provider name
649 db.execSQL("ALTER TABLE favorites " +
650 "ADD COLUMN appWidgetProvider TEXT;");
651 db.setTransactionSuccessful();
652 } catch (SQLException ex) {
653 Log.e(TAG, ex.getMessage(), ex);
654 // Old version remains, which means we wipe old data
655 break;
656 } finally {
657 db.endTransaction();
658 }
659 }
660 case 14: {
661 db.beginTransaction();
662 try {
663 // Insert new column for holding update timestamp
664 db.execSQL("ALTER TABLE favorites " +
665 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
666 db.execSQL("ALTER TABLE workspaceScreens " +
667 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
668 db.setTransactionSuccessful();
669 } catch (SQLException ex) {
670 Log.e(TAG, ex.getMessage(), ex);
671 // Old version remains, which means we wipe old data
672 break;
673 } finally {
674 db.endTransaction();
675 }
676 }
677 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700678 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800679 // Old version remains, which means we wipe old data
680 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 }
682 }
683 case 16: {
684 // We use the db version upgrade here to identify users who may not have seen
685 // clings yet (because they weren't available), but for whom the clings are now
686 // available (tablet users). Because one of the possible cling flows (migration)
687 // is very destructive (wipes out workspaces), we want to prevent this from showing
688 // until clear data. We do so by marking that the clings have been shown.
689 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
690 }
691 case 17: {
692 // No-op
693 }
694 case 18: {
695 // Due to a data loss bug, some users may have items associated with screen ids
696 // which no longer exist. Since this can cause other problems, and since the user
697 // will never see these items anyway, we use database upgrade as an opportunity to
698 // clean things up.
699 removeOrphanedItems(db);
700 }
701 case 19: {
702 // Add userId column
703 if (!addProfileColumn(db)) {
704 // Old version remains, which means we wipe old data
705 break;
706 }
707 }
708 case 20:
709 if (!updateFolderItemsRank(db, true)) {
710 break;
711 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800712 case 21:
713 // Recreate workspace table with screen id a primary key
714 if (!recreateWorkspaceTable(db)) {
715 break;
716 }
717 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700718 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
719 // Old version remains, which means we wipe old data
720 break;
721 }
722 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700723 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700724 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700725 case 24:
726 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700727 case 25:
728 convertShortcutsToLauncherActivities(db);
729 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800730 // DB Upgraded successfully
731 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400732 }
733 }
734
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 // DB was not upgraded
736 Log.w(TAG, "Destroying all old data.");
737 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800738 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800739
Adam Cohen9b1d0622014-05-21 19:01:57 -0700740 @Override
741 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
742 // This shouldn't happen -- throw our hands up in the air and start over.
743 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
744 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700745 createEmptyDB(db);
746 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700747
Sunny Goyal42de82f2014-09-26 22:09:29 -0700748 /**
749 * Clears all the data for a fresh start.
750 */
751 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700752 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
753 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
754 onCreate(db);
755 }
756
Sunny Goyald2f38192015-02-25 10:46:34 -0800757 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700758 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
759 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
760 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700761 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700762 db.beginTransaction();
763 Cursor c = null;
764 SQLiteStatement updateStmt = null;
765
766 try {
767 // Only consider the primary user as other users can't have a shortcut.
768 long userSerial = UserManagerCompat.getInstance(mContext)
769 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
770 c = db.query(TABLE_FAVORITES, new String[] {
771 Favorites._ID,
772 Favorites.INTENT,
773 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
774 null, null, null, null);
775
776 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
777 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
778
779 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
780 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
781
782 while (c.moveToNext()) {
783 String intentDescription = c.getString(intentIndex);
784 Intent intent;
785 try {
786 intent = Intent.parseUri(intentDescription, 0);
787 } catch (URISyntaxException e) {
788 Log.e(TAG, "Unable to parse intent", e);
789 continue;
790 }
791
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700792 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700793 continue;
794 }
795
796 long id = c.getLong(idIndex);
797 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700798 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700799 }
800 db.setTransactionSuccessful();
801 } catch (SQLException ex) {
802 Log.w(TAG, "Error deduping shortcuts", ex);
803 } finally {
804 db.endTransaction();
805 if (c != null) {
806 c.close();
807 }
808 if (updateStmt != null) {
809 updateStmt.close();
810 }
811 }
812 }
813
814 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800815 * Recreates workspace table and migrates data to the new table.
816 */
817 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
818 db.beginTransaction();
819 try {
820 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
821 new String[] {LauncherSettings.WorkspaceScreens._ID},
822 null, null, null, null,
823 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
824 ArrayList<Long> sortedIDs = new ArrayList<Long>();
825 long maxId = 0;
826 try {
827 while (c.moveToNext()) {
828 Long id = c.getLong(0);
829 if (!sortedIDs.contains(id)) {
830 sortedIDs.add(id);
831 maxId = Math.max(maxId, id);
832 }
833 }
834 } finally {
835 c.close();
836 }
837
838 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700839 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800840
841 // Add all screen ids back
842 int total = sortedIDs.size();
843 for (int i = 0; i < total; i++) {
844 ContentValues values = new ContentValues();
845 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
846 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
847 addModifiedTime(values);
848 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
849 }
850 db.setTransactionSuccessful();
851 mMaxScreenId = maxId;
852 } catch (SQLException ex) {
853 // Old version remains, which means we wipe old data
854 Log.e(TAG, ex.getMessage(), ex);
855 return false;
856 } finally {
857 db.endTransaction();
858 }
859 return true;
860 }
861
Adam Cohen091440a2015-03-18 14:16:05 -0700862 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800863 db.beginTransaction();
864 try {
865 if (addRankColumn) {
866 // Insert new column for holding rank
867 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
868 }
869
870 // Get a map for folder ID to folder width
871 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
872 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
873 + " GROUP BY container;",
874 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
875
876 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800877 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
878 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800879 new Object[] {c.getLong(1) + 1, c.getLong(0)});
880 }
881
882 c.close();
883 db.setTransactionSuccessful();
884 } catch (SQLException ex) {
885 // Old version remains, which means we wipe old data
886 Log.e(TAG, ex.getMessage(), ex);
887 return false;
888 } finally {
889 db.endTransaction();
890 }
891 return true;
892 }
893
Kenny Guyed131872014-04-30 03:02:21 +0100894 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700895 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
896 // Default to the serial number of this user, for older
897 // shortcuts.
898 long userSerialNumber = userManager.getSerialNumberForUser(
899 UserHandleCompat.myUserHandle());
900 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
901 }
902
903 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100904 db.beginTransaction();
905 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700906 db.execSQL("ALTER TABLE favorites ADD COLUMN "
907 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100908 db.setTransactionSuccessful();
909 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100910 Log.e(TAG, ex.getMessage(), ex);
911 return false;
912 } finally {
913 db.endTransaction();
914 }
915 return true;
916 }
917
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700918 // Generates a new ID to use for an object in your database. This method should be only
919 // called from the main UI thread. As an exception, we do call it when we call the
920 // constructor from the worker thread; however, this doesn't extend until after the
921 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
922 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700923 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700924 public long generateNewItemId() {
925 if (mMaxItemId < 0) {
926 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700927 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700928 mMaxItemId += 1;
929 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700930 }
931
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700932 @Override
933 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
934 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
935 }
936
Chris Wren5dee7af2013-12-20 17:22:11 -0500937 public void checkId(String table, ContentValues values) {
938 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
939 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
940 mMaxScreenId = Math.max(id, mMaxScreenId);
941 } else {
942 mMaxItemId = Math.max(id, mMaxItemId);
943 }
944 }
945
Adam Cohendcd297f2013-06-18 13:13:40 -0700946 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800947 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 }
949
950 // Generates a new ID to use for an workspace screen in your database. This method
951 // should be only called from the main UI thread. As an exception, we do call it when we
952 // call the constructor from the worker thread; however, this doesn't extend until after the
953 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
954 // after that point
955 public long generateNewScreenId() {
956 if (mMaxScreenId < 0) {
957 throw new RuntimeException("Error: max screen id was not initialized");
958 }
959 mMaxScreenId += 1;
960 return mMaxScreenId;
961 }
962
Adam Cohendcd297f2013-06-18 13:13:40 -0700963 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800964 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800965 }
966
Adam Cohen091440a2015-03-18 14:16:05 -0700967 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700968 // 1. Ensure that externally added items have a valid item id
969 long id = generateNewItemId();
970 values.put(LauncherSettings.Favorites._ID, id);
971
972 // 2. In the case of an app widget, and if no app widget id is specified, we
973 // attempt allocate and bind the widget.
974 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
975 if (itemType != null &&
976 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
977 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
978
979 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
980 ComponentName cn = ComponentName.unflattenFromString(
981 values.getAsString(Favorites.APPWIDGET_PROVIDER));
982
983 if (cn != null) {
984 try {
985 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700986 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700987 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700988 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700989 }
990 } catch (RuntimeException e) {
991 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700992 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700993 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700994 } else {
995 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700996 }
997 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700998
999 // Add screen id if not present
1000 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
1001 if (!addScreenIdIfNecessary(screenId)) {
1002 return false;
1003 }
Adam Cohena043fa82014-07-23 14:49:38 -07001004 return true;
1005 }
1006
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001007 // Returns true of screen id exists, or if successfully added
1008 private boolean addScreenIdIfNecessary(long screenId) {
1009 if (!hasScreenId(screenId)) {
1010 int rank = getMaxScreenRank() + 1;
1011
1012 ContentValues v = new ContentValues();
1013 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1014 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1015 if (dbInsertAndCheck(this, getWritableDatabase(),
1016 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
1017 return false;
1018 }
1019 }
1020 return true;
1021 }
1022
1023 private boolean hasScreenId(long screenId) {
1024 SQLiteDatabase db = getWritableDatabase();
1025 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
1026 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
1027 if (c != null) {
1028 int count = c.getCount();
1029 c.close();
1030 return count > 0;
1031 } else {
1032 return false;
1033 }
1034 }
1035
1036 private int getMaxScreenRank() {
1037 SQLiteDatabase db = getWritableDatabase();
1038 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
1039 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
1040
1041 // get the result
1042 final int maxRankIndex = 0;
1043 int rank = -1;
1044 if (c != null && c.moveToNext()) {
1045 rank = c.getInt(maxRankIndex);
1046 }
1047 if (c != null) {
1048 c.close();
1049 }
1050
1051 return rank;
1052 }
1053
Adam Cohen091440a2015-03-18 14:16:05 -07001054 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001055 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001056 // TODO: Use multiple loaders with fall-back and transaction.
1057 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001058
1059 // Add the screens specified by the items above
1060 Collections.sort(screenIds);
1061 int rank = 0;
1062 ContentValues values = new ContentValues();
1063 for (Long id : screenIds) {
1064 values.clear();
1065 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1066 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1067 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1068 throw new RuntimeException("Failed initialize screen table"
1069 + "from default layout");
1070 }
1071 rank++;
1072 }
1073
1074 // Ensure that the max ids are initialized
1075 mMaxItemId = initializeMaxItemId(db);
1076 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001077
Adam Cohen71483f42014-05-15 14:04:01 -07001078 return count;
1079 }
1080
Adam Cohen091440a2015-03-18 14:16:05 -07001081 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001082 final ContentResolver resolver = mContext.getContentResolver();
1083 Cursor c = null;
1084 int count = 0;
1085 int curScreen = 0;
1086
1087 try {
1088 c = resolver.query(uri, null, null, null, "title ASC");
1089 } catch (Exception e) {
1090 // Ignore
1091 }
1092
Dan Sandlerd5024042014-01-09 15:01:33 -05001093 // We already have a favorites database in the old provider
1094 if (c != null) {
1095 try {
1096 if (c.getCount() > 0) {
1097 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1098 final int intentIndex
1099 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1100 final int titleIndex
1101 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1102 final int iconTypeIndex
1103 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1104 final int iconIndex
1105 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1106 final int iconPackageIndex
1107 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1108 final int iconResourceIndex
1109 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1110 final int containerIndex
1111 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1112 final int itemTypeIndex
1113 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1114 final int screenIndex
1115 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1116 final int cellXIndex
1117 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1118 final int cellYIndex
1119 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1120 final int uriIndex
1121 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1122 final int displayModeIndex
1123 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001124 final int profileIndex
1125 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001126
1127 int i = 0;
1128 int curX = 0;
1129 int curY = 0;
1130
1131 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001132 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1133 final int width = (int) profile.numColumns;
1134 final int height = (int) profile.numRows;
1135 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001136
1137 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1138
Adam Cohen72960972014-01-15 18:13:55 -08001139 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1140 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001141 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001142
1143 while (c.moveToNext()) {
1144 final int itemType = c.getInt(itemTypeIndex);
1145 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1146 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1147 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1148 continue;
1149 }
1150
1151 final int cellX = c.getInt(cellXIndex);
1152 final int cellY = c.getInt(cellYIndex);
1153 final int screen = c.getInt(screenIndex);
1154 int container = c.getInt(containerIndex);
1155 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001156
1157 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1158 UserHandleCompat userHandle;
1159 final long userSerialNumber;
1160 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1161 userSerialNumber = c.getInt(profileIndex);
1162 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1163 } else {
1164 // Default to the serial number of this user, for older
1165 // shortcuts.
1166 userHandle = UserHandleCompat.myUserHandle();
1167 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1168 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001169
1170 if (userHandle == null) {
1171 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1172 continue;
1173 }
1174
Dan Sandlerd5024042014-01-09 15:01:33 -05001175 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001176 + c.getString(titleIndex) + "\" ("
1177 + cellX + "," + cellY + "@"
1178 + LauncherSettings.Favorites.containerToString(container)
1179 + "/" + screen
1180 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001181
1182 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001183
1184 final Intent intent;
1185 final ComponentName cn;
1186 try {
1187 intent = Intent.parseUri(intentStr, 0);
1188 } catch (URISyntaxException e) {
1189 // bogus intent?
1190 Launcher.addDumpLog(TAG,
1191 "skipping invalid intent uri", true);
1192 continue;
1193 }
1194
1195 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001196 if (TextUtils.isEmpty(intentStr)) {
1197 // no intent? no icon
1198 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1199 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001200 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001201 !LauncherModel.isValidPackageActivity(mContext, cn,
1202 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001203 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001204 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001205 "no longer exists.", true);
1206 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001207 } else if (container ==
1208 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1209 // Dedupe icons directly on the workspace
1210
Adam Cohen556f6132014-01-15 15:18:08 -08001211 // Canonicalize
1212 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001213 // does not, so we clear that out to keep them the same.
1214 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001215 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001216 int flags = intent.getFlags();
1217 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001218 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001219 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001220 if (seenIntents.contains(key)) {
1221 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001222 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001223 } else {
1224 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001225 }
1226 }
1227 }
1228
1229 ContentValues values = new ContentValues(c.getColumnCount());
1230 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1231 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1232 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1233 values.put(LauncherSettings.Favorites.ICON_TYPE,
1234 c.getInt(iconTypeIndex));
1235 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1236 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1237 c.getString(iconPackageIndex));
1238 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1239 c.getString(iconResourceIndex));
1240 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1241 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1242 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1243 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1244 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001245 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001246
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001247 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1248 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001249 }
1250
1251 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1252 // In a folder or in the hotseat, preserve position
1253 values.put(LauncherSettings.Favorites.SCREEN, screen);
1254 values.put(LauncherSettings.Favorites.CELLX, cellX);
1255 values.put(LauncherSettings.Favorites.CELLY, cellY);
1256 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001257 // For items contained directly on one of the workspace screen,
1258 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001259 }
1260
1261 values.put(LauncherSettings.Favorites.CONTAINER, container);
1262
Adam Cohen72960972014-01-15 18:13:55 -08001263 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1264 shortcuts.add(values);
1265 } else {
1266 folders.add(values);
1267 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001268 }
1269
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001270 // Now that we have all the hotseat icons, let's go through them left-right
1271 // and assign valid locations for them in the new hotseat
1272 final int N = hotseat.size();
1273 for (int idx=0; idx<N; idx++) {
1274 int hotseatX = hotseat.keyAt(idx);
1275 ContentValues values = hotseat.valueAt(idx);
1276
Adam Cohen2e6da152015-05-06 11:42:25 -07001277 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001278 // let's drop this in the next available hole in the hotseat
1279 while (++hotseatX < hotseatWidth) {
1280 if (hotseat.get(hotseatX) == null) {
1281 // found a spot! move it here
1282 values.put(LauncherSettings.Favorites.SCREEN,
1283 hotseatX);
1284 break;
1285 }
1286 }
1287 }
1288 if (hotseatX >= hotseatWidth) {
1289 // no room for you in the hotseat? it's off to the desktop with you
1290 values.put(LauncherSettings.Favorites.CONTAINER,
1291 Favorites.CONTAINER_DESKTOP);
1292 }
1293 }
1294
Adam Cohen72960972014-01-15 18:13:55 -08001295 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1296 // Folders first
1297 allItems.addAll(folders);
1298 // Then shortcuts
1299 allItems.addAll(shortcuts);
1300
1301 // Layout all the folders
1302 for (ContentValues values: allItems) {
1303 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1304 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1305 // Hotseat items and folder items have already had their
1306 // location information set. Nothing to be done here.
1307 continue;
1308 }
1309 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1310 values.put(LauncherSettings.Favorites.CELLX, curX);
1311 values.put(LauncherSettings.Favorites.CELLY, curY);
1312 curX = (curX + 1) % width;
1313 if (curX == 0) {
1314 curY = (curY + 1);
1315 }
1316 // Leave the last row of icons blank on every screen
1317 if (curY == height - 1) {
1318 curScreen = (int) generateNewScreenId();
1319 curY = 0;
1320 }
1321 }
1322
1323 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001324 db.beginTransaction();
1325 try {
Adam Cohen72960972014-01-15 18:13:55 -08001326 for (ContentValues row: allItems) {
1327 if (row == null) continue;
1328 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001329 < 0) {
1330 return;
1331 } else {
1332 count++;
1333 }
1334 }
1335 db.setTransactionSuccessful();
1336 } finally {
1337 db.endTransaction();
1338 }
1339 }
1340
1341 db.beginTransaction();
1342 try {
1343 for (i=0; i<=curScreen; i++) {
1344 final ContentValues values = new ContentValues();
1345 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1346 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1347 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1348 < 0) {
1349 return;
1350 }
1351 }
1352 db.setTransactionSuccessful();
1353 } finally {
1354 db.endTransaction();
1355 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001356
1357 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001358 }
1359 } finally {
1360 c.close();
1361 }
1362 }
1363
1364 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1365 + (curScreen+1) + " screens", true);
1366
1367 // ensure that new screens are created to hold these icons
1368 setFlagJustLoadedOldDb();
1369
1370 // Update max IDs; very important since we just grabbed IDs from another database
1371 mMaxItemId = initializeMaxItemId(db);
1372 mMaxScreenId = initializeMaxScreenId(db);
1373 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1374 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001375 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001376
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001377 /**
1378 * @return the max _id in the provided table.
1379 */
Adam Cohen091440a2015-03-18 14:16:05 -07001380 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001381 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1382 // get the result
1383 long id = -1;
1384 if (c != null && c.moveToNext()) {
1385 id = c.getLong(0);
1386 }
1387 if (c != null) {
1388 c.close();
1389 }
1390
1391 if (id == -1) {
1392 throw new RuntimeException("Error: could not query max id in " + table);
1393 }
1394
1395 return id;
1396 }
1397
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001398 static class SqlArguments {
1399 public final String table;
1400 public final String where;
1401 public final String[] args;
1402
1403 SqlArguments(Uri url, String where, String[] args) {
1404 if (url.getPathSegments().size() == 1) {
1405 this.table = url.getPathSegments().get(0);
1406 this.where = where;
1407 this.args = args;
1408 } else if (url.getPathSegments().size() != 2) {
1409 throw new IllegalArgumentException("Invalid URI: " + url);
1410 } else if (!TextUtils.isEmpty(where)) {
1411 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1412 } else {
1413 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001414 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001415 this.args = null;
1416 }
1417 }
1418
1419 SqlArguments(Uri url) {
1420 if (url.getPathSegments().size() == 1) {
1421 table = url.getPathSegments().get(0);
1422 where = null;
1423 args = null;
1424 } else {
1425 throw new IllegalArgumentException("Invalid URI: " + url);
1426 }
1427 }
1428 }
Adam Cohen72960972014-01-15 18:13:55 -08001429}