blob: cb808c22be17b424a7dc97b2d3b9d3478837bd87 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ContentResolver;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000031import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070032import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070033import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070034import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.database.Cursor;
36import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
39import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070040import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070042import android.os.Binder;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Build;
44import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080046import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050050import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040056import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070057import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070059
Dan Sandlerd5024042014-01-09 15:01:33 -050060import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070061import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070062import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070063import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050064import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080067 private static final String TAG = "Launcher.LauncherProvider";
68 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Sunny Goyal5c97f512015-05-19 16:03:28 -070070 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Adam Cohene25af792013-06-06 23:08:25 -070072 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040073 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
Adam Cohena043fa82014-07-23 14:49:38 -070079 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
80
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070081 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
82
Anjali Koppal67e7cae2014-03-13 12:14:12 -070083 private LauncherProviderChangeListener mListener;
84
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070085 /**
Romain Guy73b979d2009-06-09 12:57:21 -070086 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070087 * {@link AppWidgetHost#deleteHost()} is called during database creation.
88 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
89 */
90 static final Uri CONTENT_APPWIDGET_RESET_URI =
91 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070092
Sunny Goyal316490e2015-06-02 09:38:28 -070093 @Thunk DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
95 @Override
96 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040097 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080098 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040099 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -0800100 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -0400101 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102 return true;
103 }
104
Winson Chung0b560dd2014-01-21 13:00:26 -0800105 public boolean wasNewDbCreated() {
106 return mOpenHelper.wasNewDbCreated();
107 }
108
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700109 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
110 mListener = listener;
111 }
112
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113 @Override
114 public String getType(Uri uri) {
115 SqlArguments args = new SqlArguments(uri, null, null);
116 if (TextUtils.isEmpty(args.where)) {
117 return "vnd.android.cursor.dir/" + args.table;
118 } else {
119 return "vnd.android.cursor.item/" + args.table;
120 }
121 }
122
123 @Override
124 public Cursor query(Uri uri, String[] projection, String selection,
125 String[] selectionArgs, String sortOrder) {
126
127 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
128 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
129 qb.setTables(args.table);
130
Romain Guy73b979d2009-06-09 12:57:21 -0700131 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
133 result.setNotificationUri(getContext().getContentResolver(), uri);
134
135 return result;
136 }
137
Adam Cohen091440a2015-03-18 14:16:05 -0700138 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500140 if (values == null) {
141 throw new RuntimeException("Error: attempting to insert null values");
142 }
Adam Cohen71483f42014-05-15 14:04:01 -0700143 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700144 throw new RuntimeException("Error: attempting to add item without specifying an id");
145 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500146 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 return db.insert(table, nullColumnHack, values);
148 }
149
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150 @Override
151 public Uri insert(Uri uri, ContentValues initialValues) {
152 SqlArguments args = new SqlArguments(uri);
153
Adam Cohena043fa82014-07-23 14:49:38 -0700154 // In very limited cases, we support system|signature permission apps to add to the db
155 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700156 final boolean isExternalAll = externalAdd != null && "true".equals(externalAdd);
157 if (isExternalAll) {
Adam Cohena043fa82014-07-23 14:49:38 -0700158 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
159 return null;
160 }
161 }
162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400164 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800166 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
168 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700169 notifyListeners();
170
171 if (isExternalAll) {
172 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
173 if (app != null) {
174 app.reloadWorkspace();
175 }
176 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177
178 return uri;
179 }
180
Adam Cohena043fa82014-07-23 14:49:38 -0700181
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 @Override
183 public int bulkInsert(Uri uri, ContentValues[] values) {
184 SqlArguments args = new SqlArguments(uri);
185
186 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
187 db.beginTransaction();
188 try {
189 int numValues = values.length;
190 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400191 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700192 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
193 return 0;
194 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 }
196 db.setTransactionSuccessful();
197 } finally {
198 db.endTransaction();
199 }
200
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700201 notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800202 return values.length;
203 }
204
205 @Override
Yura085c8532014-02-11 15:15:29 +0000206 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
207 throws OperationApplicationException {
208 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
209 db.beginTransaction();
210 try {
211 ContentProviderResult[] result = super.applyBatch(operations);
212 db.setTransactionSuccessful();
213 return result;
214 } finally {
215 db.endTransaction();
216 }
217 }
218
219 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 public int delete(Uri uri, String selection, String[] selectionArgs) {
221 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
222
223 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
224 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700225 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800226
227 return count;
228 }
229
230 @Override
231 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
232 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
233
Chris Wren1ada10d2013-09-13 18:01:38 -0400234 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
236 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700237 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238
239 return count;
240 }
241
Sunny Goyal7779d622015-06-11 16:18:39 -0700242 @Override
243 public Bundle call(String method, String arg, Bundle extras) {
244 if (Binder.getCallingUid() != Process.myUid()) {
245 return null;
246 }
247
248 switch (method) {
249 case LauncherSettings.Settings.METHOD_GET_BOOLEAN: {
250 Bundle result = new Bundle();
251 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
252 getContext().getSharedPreferences(
253 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
254 .getBoolean(arg, extras.getBoolean(
255 LauncherSettings.Settings.EXTRA_DEFAULT_VALUE)));
256 return result;
257 }
258 case LauncherSettings.Settings.METHOD_SET_BOOLEAN: {
259 boolean value = extras.getBoolean(LauncherSettings.Settings.EXTRA_VALUE);
260 getContext().getSharedPreferences(
261 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE)
262 .edit().putBoolean(arg, value).apply();
263 if (mListener != null) {
264 mListener.onSettingsChanged(arg, value);
265 }
266 Bundle result = new Bundle();
267 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE, value);
268 return result;
269 }
270 }
271 return null;
272 }
273
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700274 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400275 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400276 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700277 if (mListener != null) {
278 mListener.onLauncherProviderChange();
279 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400280 }
281
Adam Cohen091440a2015-03-18 14:16:05 -0700282 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400283 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 }
285
Adam Cohendcd297f2013-06-18 13:13:40 -0700286 public long generateNewItemId() {
287 return mOpenHelper.generateNewItemId();
288 }
289
Winson Chungc763c4e2013-07-19 13:49:06 -0700290 public void updateMaxItemId(long id) {
291 mOpenHelper.updateMaxItemId(id);
292 }
293
Adam Cohendcd297f2013-06-18 13:13:40 -0700294 public long generateNewScreenId() {
295 return mOpenHelper.generateNewScreenId();
296 }
297
Brian Muramatsu5524b492012-10-02 16:55:54 -0700298 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700299 * Clears all the data for a fresh start.
300 */
301 synchronized public void createEmptyDB() {
302 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
303 }
304
Sunny Goyal33d44382014-10-16 09:24:19 -0700305 public void clearFlagEmptyDbCreated() {
306 String spKey = LauncherAppState.getSharedPreferencesKey();
307 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
308 .edit()
309 .remove(EMPTY_DATABASE_CREATED)
310 .commit();
311 }
312
Sunny Goyal42de82f2014-09-26 22:09:29 -0700313 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700314 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700315 * 1) From the app restrictions
316 * 2) From a package provided by play store
317 * 3) From a partner configuration APK, already in the system image
318 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700319 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700320 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400321 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700322 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700323
Winson Chungc763c4e2013-07-19 13:49:06 -0700324 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500325 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200326
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700327 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
328 if (loader == null) {
329 loader = AutoInstallsLayout.get(getContext(),
330 mOpenHelper.mAppWidgetHost, mOpenHelper);
331 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700332 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700333 final Partner partner = Partner.get(getContext().getPackageManager());
334 if (partner != null && partner.hasDefaultLayout()) {
335 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700336 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700337 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700338 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700339 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
340 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700341 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700342 }
343 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700344
Sunny Goyal9d219682014-10-23 14:21:02 -0700345 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700346 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700347 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700348 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800349
350 // There might be some partially restored DB items, due to buggy restore logic in
351 // previous versions of launcher.
352 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700353 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700354 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
355 && usingExternallyProvidedLayout) {
356 // Unable to load external layout. Cleanup and load the internal layout.
357 createEmptyDB();
358 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
359 getDefaultLayoutParser());
360 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700361 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700362 }
363 }
364
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700365 /**
366 * Creates workspace loader from an XML resource listed in the app restrictions.
367 *
368 * @return the loader if the restrictions are set and the resource exists; null otherwise.
369 */
370 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
371 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
372 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
373 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
374 return null;
375 }
376
377 Context ctx = getContext();
378 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
379 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700380 if (bundle == null) {
381 return null;
382 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700383
Sunny Goyal35ca8732015-04-06 10:45:31 -0700384 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700385 if (packageName != null) {
386 try {
387 Resources targetResources = ctx.getPackageManager()
388 .getResourcesForApplication(packageName);
389 return AutoInstallsLayout.get(ctx, packageName, targetResources,
390 mOpenHelper.mAppWidgetHost, mOpenHelper);
391 } catch (NameNotFoundException e) {
392 Log.e(TAG, "Target package for restricted profile not found", e);
393 return null;
394 }
395 }
396 return null;
397 }
398
Sunny Goyal9d219682014-10-23 14:21:02 -0700399 private DefaultLayoutParser getDefaultLayoutParser() {
400 int defaultLayout = LauncherAppState.getInstance()
Adam Cohen2e6da152015-05-06 11:42:25 -0700401 .getInvariantDeviceProfile().defaultLayoutId;
Sunny Goyal9d219682014-10-23 14:21:02 -0700402 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
403 mOpenHelper, getContext().getResources(), defaultLayout);
404 }
405
Dan Sandlerd5024042014-01-09 15:01:33 -0500406 public void migrateLauncher2Shortcuts() {
407 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400408 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500409 }
410
Sunny Goyal08f72612015-01-05 13:41:43 -0800411 public void updateFolderItemsRank() {
412 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
413 }
414
Sunny Goyal5c97f512015-05-19 16:03:28 -0700415 public void convertShortcutsToLauncherActivities() {
416 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
417 }
418
419
Dan Sandlerd5024042014-01-09 15:01:33 -0500420 public void deleteDatabase() {
421 // Are you sure? (y/n)
422 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500423 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500424 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500425 if (dbFile.exists()) {
426 SQLiteDatabase.deleteDatabase(dbFile);
427 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500428 mOpenHelper = new DatabaseHelper(getContext());
429 }
430
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700431 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800432 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700433 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700434 private long mMaxItemId = -1;
435 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800436
Winson Chung0b560dd2014-01-21 13:00:26 -0800437 private boolean mNewDbCreated = false;
438
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800439 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100440 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800441 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700442 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700443
444 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
445 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700446 if (mMaxItemId == -1) {
447 mMaxItemId = initializeMaxItemId(getWritableDatabase());
448 }
449 if (mMaxScreenId == -1) {
450 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700451 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800452 }
453
Winson Chung0b560dd2014-01-21 13:00:26 -0800454 public boolean wasNewDbCreated() {
455 return mNewDbCreated;
456 }
457
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700458 /**
459 * Send notification that we've deleted the {@link AppWidgetHost},
460 * probably as part of the initial database creation. The receiver may
461 * want to re-call {@link AppWidgetHost#startListening()} to ensure
462 * callbacks are correctly set.
463 */
464 private void sendAppWidgetResetNotify() {
465 final ContentResolver resolver = mContext.getContentResolver();
466 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
467 }
468
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800469 @Override
470 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800471 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700472
Adam Cohendcd297f2013-06-18 13:13:40 -0700473 mMaxItemId = 1;
474 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800475 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700476
Kenny Guyed131872014-04-30 03:02:21 +0100477 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
478 long userSerialNumber = userManager.getSerialNumberForUser(
479 UserHandleCompat.myUserHandle());
480
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800481 db.execSQL("CREATE TABLE favorites (" +
482 "_id INTEGER PRIMARY KEY," +
483 "title TEXT," +
484 "intent TEXT," +
485 "container INTEGER," +
486 "screen INTEGER," +
487 "cellX INTEGER," +
488 "cellY INTEGER," +
489 "spanX INTEGER," +
490 "spanY INTEGER," +
491 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700492 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800493 "isShortcut INTEGER," +
494 "iconType INTEGER," +
495 "iconPackage TEXT," +
496 "iconResource TEXT," +
497 "icon BLOB," +
498 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400499 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400500 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500501 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100502 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800503 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700504 "rank INTEGER NOT NULL DEFAULT 0," +
505 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800506 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700507 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800508
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700509 // Database was just created, so wipe any previous widgets
510 if (mAppWidgetHost != null) {
511 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700512 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800513 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700514
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800515 // Fresh and clean launcher DB.
516 mMaxItemId = initializeMaxItemId(db);
517 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700518
519 // When a new DB is created, remove all previously stored managed profile information.
520 ManagedProfileHeuristic.processAllUsers(Collections.EMPTY_LIST, mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800521 }
522
Adam Cohendcd297f2013-06-18 13:13:40 -0700523 private void addWorkspacesTable(SQLiteDatabase db) {
524 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800525 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400526 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
527 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700528 ");");
529 }
530
Adam Cohen119285e2014-04-02 16:59:08 -0700531 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700532 // Delete items directly on the workspace who's screen id doesn't exist
533 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
534 // AND container = -100"
535 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
536 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700537 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700538 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
539 " AND " +
540 LauncherSettings.Favorites.CONTAINER + " = " +
541 LauncherSettings.Favorites.CONTAINER_DESKTOP;
542 db.execSQL(removeOrphanedDesktopItems);
543
544 // Delete items contained in folders which no longer exist (after above statement)
545 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
546 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
547 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
548 " WHERE " +
549 LauncherSettings.Favorites.CONTAINER + " <> " +
550 LauncherSettings.Favorites.CONTAINER_DESKTOP +
551 " AND "
552 + LauncherSettings.Favorites.CONTAINER + " <> " +
553 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
554 " AND "
555 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
556 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
557 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
558 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
559 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700560 }
561
Winson Chungc763c4e2013-07-19 13:49:06 -0700562 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400563 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700564 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800565 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700566 }
567
Winson Chungc763c4e2013-07-19 13:49:06 -0700568 private void setFlagEmptyDbCreated() {
569 String spKey = LauncherAppState.getSharedPreferencesKey();
570 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800571 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700572 }
573
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 @Override
575 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700576 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800577 switch (oldVersion) {
578 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800579 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800580 case 12: {
581 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
582 // to persist workspace screens and their relative order.
583 mMaxScreenId = 0;
584 addWorkspacesTable(db);
585 }
586 case 13: {
587 db.beginTransaction();
588 try {
589 // Insert new column for holding widget provider name
590 db.execSQL("ALTER TABLE favorites " +
591 "ADD COLUMN appWidgetProvider TEXT;");
592 db.setTransactionSuccessful();
593 } catch (SQLException ex) {
594 Log.e(TAG, ex.getMessage(), ex);
595 // Old version remains, which means we wipe old data
596 break;
597 } finally {
598 db.endTransaction();
599 }
600 }
601 case 14: {
602 db.beginTransaction();
603 try {
604 // Insert new column for holding update timestamp
605 db.execSQL("ALTER TABLE favorites " +
606 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
607 db.execSQL("ALTER TABLE workspaceScreens " +
608 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
609 db.setTransactionSuccessful();
610 } catch (SQLException ex) {
611 Log.e(TAG, ex.getMessage(), ex);
612 // Old version remains, which means we wipe old data
613 break;
614 } finally {
615 db.endTransaction();
616 }
617 }
618 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700619 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800620 // Old version remains, which means we wipe old data
621 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800622 }
623 }
624 case 16: {
625 // We use the db version upgrade here to identify users who may not have seen
626 // clings yet (because they weren't available), but for whom the clings are now
627 // available (tablet users). Because one of the possible cling flows (migration)
628 // is very destructive (wipes out workspaces), we want to prevent this from showing
629 // until clear data. We do so by marking that the clings have been shown.
630 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
631 }
632 case 17: {
633 // No-op
634 }
635 case 18: {
636 // Due to a data loss bug, some users may have items associated with screen ids
637 // which no longer exist. Since this can cause other problems, and since the user
638 // will never see these items anyway, we use database upgrade as an opportunity to
639 // clean things up.
640 removeOrphanedItems(db);
641 }
642 case 19: {
643 // Add userId column
644 if (!addProfileColumn(db)) {
645 // Old version remains, which means we wipe old data
646 break;
647 }
648 }
649 case 20:
650 if (!updateFolderItemsRank(db, true)) {
651 break;
652 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800653 case 21:
654 // Recreate workspace table with screen id a primary key
655 if (!recreateWorkspaceTable(db)) {
656 break;
657 }
658 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700659 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
660 // Old version remains, which means we wipe old data
661 break;
662 }
663 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700664 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700665 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700666 case 24:
667 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700668 case 25:
669 convertShortcutsToLauncherActivities(db);
670 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 // DB Upgraded successfully
672 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400673 }
674 }
675
Sunny Goyala2cc6242015-01-14 14:23:02 -0800676 // DB was not upgraded
677 Log.w(TAG, "Destroying all old data.");
678 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800680
Adam Cohen9b1d0622014-05-21 19:01:57 -0700681 @Override
682 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
683 // This shouldn't happen -- throw our hands up in the air and start over.
684 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
685 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700686 createEmptyDB(db);
687 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700688
Sunny Goyal42de82f2014-09-26 22:09:29 -0700689 /**
690 * Clears all the data for a fresh start.
691 */
692 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700693 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
694 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
695 onCreate(db);
696 }
697
Sunny Goyald2f38192015-02-25 10:46:34 -0800698 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700699 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
700 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
701 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700702 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700703 db.beginTransaction();
704 Cursor c = null;
705 SQLiteStatement updateStmt = null;
706
707 try {
708 // Only consider the primary user as other users can't have a shortcut.
709 long userSerial = UserManagerCompat.getInstance(mContext)
710 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
711 c = db.query(TABLE_FAVORITES, new String[] {
712 Favorites._ID,
713 Favorites.INTENT,
714 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
715 null, null, null, null);
716
717 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
718 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
719
720 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
721 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
722
723 while (c.moveToNext()) {
724 String intentDescription = c.getString(intentIndex);
725 Intent intent;
726 try {
727 intent = Intent.parseUri(intentDescription, 0);
728 } catch (URISyntaxException e) {
729 Log.e(TAG, "Unable to parse intent", e);
730 continue;
731 }
732
733 if (!InstallShortcutReceiver.isLauncherActivity(intent, mContext)) {
734 continue;
735 }
736
737 long id = c.getLong(idIndex);
738 updateStmt.bindLong(1, id);
739 updateStmt.execute();
740 }
741 db.setTransactionSuccessful();
742 } catch (SQLException ex) {
743 Log.w(TAG, "Error deduping shortcuts", ex);
744 } finally {
745 db.endTransaction();
746 if (c != null) {
747 c.close();
748 }
749 if (updateStmt != null) {
750 updateStmt.close();
751 }
752 }
753 }
754
755 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800756 * Recreates workspace table and migrates data to the new table.
757 */
758 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
759 db.beginTransaction();
760 try {
761 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
762 new String[] {LauncherSettings.WorkspaceScreens._ID},
763 null, null, null, null,
764 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
765 ArrayList<Long> sortedIDs = new ArrayList<Long>();
766 long maxId = 0;
767 try {
768 while (c.moveToNext()) {
769 Long id = c.getLong(0);
770 if (!sortedIDs.contains(id)) {
771 sortedIDs.add(id);
772 maxId = Math.max(maxId, id);
773 }
774 }
775 } finally {
776 c.close();
777 }
778
779 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
780 addWorkspacesTable(db);
781
782 // Add all screen ids back
783 int total = sortedIDs.size();
784 for (int i = 0; i < total; i++) {
785 ContentValues values = new ContentValues();
786 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
787 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
788 addModifiedTime(values);
789 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
790 }
791 db.setTransactionSuccessful();
792 mMaxScreenId = maxId;
793 } catch (SQLException ex) {
794 // Old version remains, which means we wipe old data
795 Log.e(TAG, ex.getMessage(), ex);
796 return false;
797 } finally {
798 db.endTransaction();
799 }
800 return true;
801 }
802
Adam Cohen091440a2015-03-18 14:16:05 -0700803 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800804 db.beginTransaction();
805 try {
806 if (addRankColumn) {
807 // Insert new column for holding rank
808 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
809 }
810
811 // Get a map for folder ID to folder width
812 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
813 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
814 + " GROUP BY container;",
815 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
816
817 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800818 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
819 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800820 new Object[] {c.getLong(1) + 1, c.getLong(0)});
821 }
822
823 c.close();
824 db.setTransactionSuccessful();
825 } catch (SQLException ex) {
826 // Old version remains, which means we wipe old data
827 Log.e(TAG, ex.getMessage(), ex);
828 return false;
829 } finally {
830 db.endTransaction();
831 }
832 return true;
833 }
834
Kenny Guyed131872014-04-30 03:02:21 +0100835 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700836 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
837 // Default to the serial number of this user, for older
838 // shortcuts.
839 long userSerialNumber = userManager.getSerialNumberForUser(
840 UserHandleCompat.myUserHandle());
841 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
842 }
843
844 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100845 db.beginTransaction();
846 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700847 db.execSQL("ALTER TABLE favorites ADD COLUMN "
848 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100849 db.setTransactionSuccessful();
850 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100851 Log.e(TAG, ex.getMessage(), ex);
852 return false;
853 } finally {
854 db.endTransaction();
855 }
856 return true;
857 }
858
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700859 // Generates a new ID to use for an object in your database. This method should be only
860 // called from the main UI thread. As an exception, we do call it when we call the
861 // constructor from the worker thread; however, this doesn't extend until after the
862 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
863 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700864 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700865 public long generateNewItemId() {
866 if (mMaxItemId < 0) {
867 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700868 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700869 mMaxItemId += 1;
870 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700871 }
872
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700873 @Override
874 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
875 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
876 }
877
Winson Chungc763c4e2013-07-19 13:49:06 -0700878 public void updateMaxItemId(long id) {
879 mMaxItemId = id + 1;
880 }
881
Chris Wren5dee7af2013-12-20 17:22:11 -0500882 public void checkId(String table, ContentValues values) {
883 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
884 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
885 mMaxScreenId = Math.max(id, mMaxScreenId);
886 } else {
887 mMaxItemId = Math.max(id, mMaxItemId);
888 }
889 }
890
Adam Cohendcd297f2013-06-18 13:13:40 -0700891 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800892 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700893 }
894
895 // Generates a new ID to use for an workspace screen in your database. This method
896 // should be only called from the main UI thread. As an exception, we do call it when we
897 // call the constructor from the worker thread; however, this doesn't extend until after the
898 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
899 // after that point
900 public long generateNewScreenId() {
901 if (mMaxScreenId < 0) {
902 throw new RuntimeException("Error: max screen id was not initialized");
903 }
904 mMaxScreenId += 1;
905 return mMaxScreenId;
906 }
907
Adam Cohendcd297f2013-06-18 13:13:40 -0700908 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800909 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800910 }
911
Adam Cohen091440a2015-03-18 14:16:05 -0700912 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700913 // 1. Ensure that externally added items have a valid item id
914 long id = generateNewItemId();
915 values.put(LauncherSettings.Favorites._ID, id);
916
917 // 2. In the case of an app widget, and if no app widget id is specified, we
918 // attempt allocate and bind the widget.
919 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
920 if (itemType != null &&
921 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
922 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
923
924 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
925 ComponentName cn = ComponentName.unflattenFromString(
926 values.getAsString(Favorites.APPWIDGET_PROVIDER));
927
928 if (cn != null) {
929 try {
930 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700931 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700932 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700933 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700934 }
935 } catch (RuntimeException e) {
936 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700937 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700938 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700939 } else {
940 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700941 }
942 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700943
944 // Add screen id if not present
945 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
946 if (!addScreenIdIfNecessary(screenId)) {
947 return false;
948 }
Adam Cohena043fa82014-07-23 14:49:38 -0700949 return true;
950 }
951
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700952 // Returns true of screen id exists, or if successfully added
953 private boolean addScreenIdIfNecessary(long screenId) {
954 if (!hasScreenId(screenId)) {
955 int rank = getMaxScreenRank() + 1;
956
957 ContentValues v = new ContentValues();
958 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
959 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
960 if (dbInsertAndCheck(this, getWritableDatabase(),
961 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
962 return false;
963 }
964 }
965 return true;
966 }
967
968 private boolean hasScreenId(long screenId) {
969 SQLiteDatabase db = getWritableDatabase();
970 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
971 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
972 if (c != null) {
973 int count = c.getCount();
974 c.close();
975 return count > 0;
976 } else {
977 return false;
978 }
979 }
980
981 private int getMaxScreenRank() {
982 SQLiteDatabase db = getWritableDatabase();
983 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
984 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
985
986 // get the result
987 final int maxRankIndex = 0;
988 int rank = -1;
989 if (c != null && c.moveToNext()) {
990 rank = c.getInt(maxRankIndex);
991 }
992 if (c != null) {
993 c.close();
994 }
995
996 return rank;
997 }
998
Adam Cohen091440a2015-03-18 14:16:05 -0700999 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001000 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001001 // TODO: Use multiple loaders with fall-back and transaction.
1002 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001003
1004 // Add the screens specified by the items above
1005 Collections.sort(screenIds);
1006 int rank = 0;
1007 ContentValues values = new ContentValues();
1008 for (Long id : screenIds) {
1009 values.clear();
1010 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1011 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
1012 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
1013 throw new RuntimeException("Failed initialize screen table"
1014 + "from default layout");
1015 }
1016 rank++;
1017 }
1018
1019 // Ensure that the max ids are initialized
1020 mMaxItemId = initializeMaxItemId(db);
1021 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001022
Adam Cohen71483f42014-05-15 14:04:01 -07001023 return count;
1024 }
1025
Adam Cohen091440a2015-03-18 14:16:05 -07001026 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001027 final ContentResolver resolver = mContext.getContentResolver();
1028 Cursor c = null;
1029 int count = 0;
1030 int curScreen = 0;
1031
1032 try {
1033 c = resolver.query(uri, null, null, null, "title ASC");
1034 } catch (Exception e) {
1035 // Ignore
1036 }
1037
Dan Sandlerd5024042014-01-09 15:01:33 -05001038 // We already have a favorites database in the old provider
1039 if (c != null) {
1040 try {
1041 if (c.getCount() > 0) {
1042 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1043 final int intentIndex
1044 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1045 final int titleIndex
1046 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1047 final int iconTypeIndex
1048 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1049 final int iconIndex
1050 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1051 final int iconPackageIndex
1052 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1053 final int iconResourceIndex
1054 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1055 final int containerIndex
1056 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1057 final int itemTypeIndex
1058 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1059 final int screenIndex
1060 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1061 final int cellXIndex
1062 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1063 final int cellYIndex
1064 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1065 final int uriIndex
1066 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1067 final int displayModeIndex
1068 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001069 final int profileIndex
1070 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001071
1072 int i = 0;
1073 int curX = 0;
1074 int curY = 0;
1075
1076 final LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07001077 final InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
1078 final int width = (int) profile.numColumns;
1079 final int height = (int) profile.numRows;
1080 final int hotseatWidth = (int) profile.numHotseatIcons;
Dan Sandlerd5024042014-01-09 15:01:33 -05001081
1082 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1083
Adam Cohen72960972014-01-15 18:13:55 -08001084 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1085 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001086 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001087
1088 while (c.moveToNext()) {
1089 final int itemType = c.getInt(itemTypeIndex);
1090 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1091 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1092 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1093 continue;
1094 }
1095
1096 final int cellX = c.getInt(cellXIndex);
1097 final int cellY = c.getInt(cellYIndex);
1098 final int screen = c.getInt(screenIndex);
1099 int container = c.getInt(containerIndex);
1100 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001101
1102 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1103 UserHandleCompat userHandle;
1104 final long userSerialNumber;
1105 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1106 userSerialNumber = c.getInt(profileIndex);
1107 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1108 } else {
1109 // Default to the serial number of this user, for older
1110 // shortcuts.
1111 userHandle = UserHandleCompat.myUserHandle();
1112 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1113 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001114
1115 if (userHandle == null) {
1116 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1117 continue;
1118 }
1119
Dan Sandlerd5024042014-01-09 15:01:33 -05001120 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001121 + c.getString(titleIndex) + "\" ("
1122 + cellX + "," + cellY + "@"
1123 + LauncherSettings.Favorites.containerToString(container)
1124 + "/" + screen
1125 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001126
1127 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001128
1129 final Intent intent;
1130 final ComponentName cn;
1131 try {
1132 intent = Intent.parseUri(intentStr, 0);
1133 } catch (URISyntaxException e) {
1134 // bogus intent?
1135 Launcher.addDumpLog(TAG,
1136 "skipping invalid intent uri", true);
1137 continue;
1138 }
1139
1140 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001141 if (TextUtils.isEmpty(intentStr)) {
1142 // no intent? no icon
1143 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1144 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001145 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001146 !LauncherModel.isValidPackageActivity(mContext, cn,
1147 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001148 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001149 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001150 "no longer exists.", true);
1151 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001152 } else if (container ==
1153 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1154 // Dedupe icons directly on the workspace
1155
Adam Cohen556f6132014-01-15 15:18:08 -08001156 // Canonicalize
1157 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001158 // does not, so we clear that out to keep them the same.
1159 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001160 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001161 int flags = intent.getFlags();
1162 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001163 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001164 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001165 if (seenIntents.contains(key)) {
1166 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001167 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001168 } else {
1169 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001170 }
1171 }
1172 }
1173
1174 ContentValues values = new ContentValues(c.getColumnCount());
1175 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1176 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1177 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1178 values.put(LauncherSettings.Favorites.ICON_TYPE,
1179 c.getInt(iconTypeIndex));
1180 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1181 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1182 c.getString(iconPackageIndex));
1183 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1184 c.getString(iconResourceIndex));
1185 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1186 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1187 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1188 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1189 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001190 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001191
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001192 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1193 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001194 }
1195
1196 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1197 // In a folder or in the hotseat, preserve position
1198 values.put(LauncherSettings.Favorites.SCREEN, screen);
1199 values.put(LauncherSettings.Favorites.CELLX, cellX);
1200 values.put(LauncherSettings.Favorites.CELLY, cellY);
1201 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001202 // For items contained directly on one of the workspace screen,
1203 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001204 }
1205
1206 values.put(LauncherSettings.Favorites.CONTAINER, container);
1207
Adam Cohen72960972014-01-15 18:13:55 -08001208 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1209 shortcuts.add(values);
1210 } else {
1211 folders.add(values);
1212 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001213 }
1214
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001215 // Now that we have all the hotseat icons, let's go through them left-right
1216 // and assign valid locations for them in the new hotseat
1217 final int N = hotseat.size();
1218 for (int idx=0; idx<N; idx++) {
1219 int hotseatX = hotseat.keyAt(idx);
1220 ContentValues values = hotseat.valueAt(idx);
1221
Adam Cohen2e6da152015-05-06 11:42:25 -07001222 if (hotseatX == profile.hotseatAllAppsRank) {
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001223 // let's drop this in the next available hole in the hotseat
1224 while (++hotseatX < hotseatWidth) {
1225 if (hotseat.get(hotseatX) == null) {
1226 // found a spot! move it here
1227 values.put(LauncherSettings.Favorites.SCREEN,
1228 hotseatX);
1229 break;
1230 }
1231 }
1232 }
1233 if (hotseatX >= hotseatWidth) {
1234 // no room for you in the hotseat? it's off to the desktop with you
1235 values.put(LauncherSettings.Favorites.CONTAINER,
1236 Favorites.CONTAINER_DESKTOP);
1237 }
1238 }
1239
Adam Cohen72960972014-01-15 18:13:55 -08001240 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1241 // Folders first
1242 allItems.addAll(folders);
1243 // Then shortcuts
1244 allItems.addAll(shortcuts);
1245
1246 // Layout all the folders
1247 for (ContentValues values: allItems) {
1248 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1249 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1250 // Hotseat items and folder items have already had their
1251 // location information set. Nothing to be done here.
1252 continue;
1253 }
1254 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1255 values.put(LauncherSettings.Favorites.CELLX, curX);
1256 values.put(LauncherSettings.Favorites.CELLY, curY);
1257 curX = (curX + 1) % width;
1258 if (curX == 0) {
1259 curY = (curY + 1);
1260 }
1261 // Leave the last row of icons blank on every screen
1262 if (curY == height - 1) {
1263 curScreen = (int) generateNewScreenId();
1264 curY = 0;
1265 }
1266 }
1267
1268 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001269 db.beginTransaction();
1270 try {
Adam Cohen72960972014-01-15 18:13:55 -08001271 for (ContentValues row: allItems) {
1272 if (row == null) continue;
1273 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001274 < 0) {
1275 return;
1276 } else {
1277 count++;
1278 }
1279 }
1280 db.setTransactionSuccessful();
1281 } finally {
1282 db.endTransaction();
1283 }
1284 }
1285
1286 db.beginTransaction();
1287 try {
1288 for (i=0; i<=curScreen; i++) {
1289 final ContentValues values = new ContentValues();
1290 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1291 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1292 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1293 < 0) {
1294 return;
1295 }
1296 }
1297 db.setTransactionSuccessful();
1298 } finally {
1299 db.endTransaction();
1300 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001301
1302 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001303 }
1304 } finally {
1305 c.close();
1306 }
1307 }
1308
1309 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1310 + (curScreen+1) + " screens", true);
1311
1312 // ensure that new screens are created to hold these icons
1313 setFlagJustLoadedOldDb();
1314
1315 // Update max IDs; very important since we just grabbed IDs from another database
1316 mMaxItemId = initializeMaxItemId(db);
1317 mMaxScreenId = initializeMaxScreenId(db);
1318 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1319 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001320 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001321
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001322 /**
1323 * @return the max _id in the provided table.
1324 */
Adam Cohen091440a2015-03-18 14:16:05 -07001325 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001326 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1327 // get the result
1328 long id = -1;
1329 if (c != null && c.moveToNext()) {
1330 id = c.getLong(0);
1331 }
1332 if (c != null) {
1333 c.close();
1334 }
1335
1336 if (id == -1) {
1337 throw new RuntimeException("Error: could not query max id in " + table);
1338 }
1339
1340 return id;
1341 }
1342
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001343 static class SqlArguments {
1344 public final String table;
1345 public final String where;
1346 public final String[] args;
1347
1348 SqlArguments(Uri url, String where, String[] args) {
1349 if (url.getPathSegments().size() == 1) {
1350 this.table = url.getPathSegments().get(0);
1351 this.where = where;
1352 this.args = args;
1353 } else if (url.getPathSegments().size() != 2) {
1354 throw new IllegalArgumentException("Invalid URI: " + url);
1355 } else if (!TextUtils.isEmpty(where)) {
1356 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1357 } else {
1358 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001359 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001360 this.args = null;
1361 }
1362 }
1363
1364 SqlArguments(Uri url) {
1365 if (url.getPathSegments().size() == 1) {
1366 table = url.getPathSegments().get(0);
1367 where = null;
1368 args = null;
1369 } else {
1370 throw new IllegalArgumentException("Invalid URI: " + url);
1371 }
1372 }
1373 }
Adam Cohen72960972014-01-15 18:13:55 -08001374}