blob: 8fef32daac7a652e850c82972f6dccc4e6855fe9 [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 Goyalb2d46ce2015-03-26 11:32:11 -070042import android.os.Build;
43import android.os.Bundle;
Nilesh Agrawalfde11852015-01-21 11:50:57 -080044import android.os.StrictMode;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070045import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070046import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080047import android.util.Log;
Dan Sandlerab5fa3a2014-03-06 23:48:04 -050048import android.util.SparseArray;
Adam Cohen228da5a2011-07-27 22:23:47 -070049
Sunny Goyal0fe505b2014-08-06 09:55:36 -070050import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
51import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010052import com.android.launcher3.compat.UserHandleCompat;
53import com.android.launcher3.compat.UserManagerCompat;
Chris Wrene523e702013-10-09 10:36:55 -040054import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fba6c2015-05-12 10:39:59 -070055import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070056import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070057
Dan Sandlerd5024042014-01-09 15:01:33 -050058import java.io.File;
Mike Cleronb87bd162009-10-30 16:36:56 -070059import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070060import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070061import java.util.Collections;
Dan Sandlerd5024042014-01-09 15:01:33 -050062import java.util.HashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064public class LauncherProvider extends ContentProvider {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080065 private static final String TAG = "Launcher.LauncherProvider";
66 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067
Sunny Goyal5c97f512015-05-19 16:03:28 -070068 private static final int DATABASE_VERSION = 26;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Adam Cohene25af792013-06-06 23:08:25 -070070 static final String OLD_AUTHORITY = "com.android.launcher2.settings";
Chris Wrene523e702013-10-09 10:36:55 -040071 static final String AUTHORITY = ProviderConfig.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070072
Sunny Goyal18b640c2015-04-17 09:24:01 -070073 static final String TABLE_FAVORITES = LauncherSettings.Favorites.TABLE_NAME;
74 static final String TABLE_WORKSPACE_SCREENS = LauncherSettings.WorkspaceScreens.TABLE_NAME;
Sunny Goyale87e6ab2014-11-21 22:42:53 -080075 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Adam Cohena043fa82014-07-23 14:49:38 -070077 private static final String URI_PARAM_IS_EXTERNAL_ADD = "isExternalAdd";
78
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070079 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
80
Anjali Koppal67e7cae2014-03-13 12:14:12 -070081 private LauncherProviderChangeListener mListener;
82
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070083 /**
Romain Guy73b979d2009-06-09 12:57:21 -070084 * {@link Uri} triggered at any registered {@link android.database.ContentObserver} when
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -070085 * {@link AppWidgetHost#deleteHost()} is called during database creation.
86 * Use this to recall {@link AppWidgetHost#startListening()} if needed.
87 */
88 static final Uri CONTENT_APPWIDGET_RESET_URI =
89 Uri.parse("content://" + AUTHORITY + "/appWidgetReset");
Daniel Lehmannc3a80402012-04-23 21:35:11 -070090
Michael Jurkaa8c760d2011-04-28 14:59:33 -070091 private DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
93 @Override
94 public boolean onCreate() {
Daniel Sandlere4f98912013-06-25 15:13:26 -040095 final Context context = getContext();
Nilesh Agrawala258f812015-01-26 14:07:29 -080096 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
Daniel Sandlere4f98912013-06-25 15:13:26 -040097 mOpenHelper = new DatabaseHelper(context);
Nilesh Agrawalfde11852015-01-21 11:50:57 -080098 StrictMode.setThreadPolicy(oldPolicy);
Daniel Sandlere4f98912013-06-25 15:13:26 -040099 LauncherAppState.setLauncherProvider(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100 return true;
101 }
102
Winson Chung0b560dd2014-01-21 13:00:26 -0800103 public boolean wasNewDbCreated() {
104 return mOpenHelper.wasNewDbCreated();
105 }
106
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700107 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
108 mListener = listener;
109 }
110
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111 @Override
112 public String getType(Uri uri) {
113 SqlArguments args = new SqlArguments(uri, null, null);
114 if (TextUtils.isEmpty(args.where)) {
115 return "vnd.android.cursor.dir/" + args.table;
116 } else {
117 return "vnd.android.cursor.item/" + args.table;
118 }
119 }
120
121 @Override
122 public Cursor query(Uri uri, String[] projection, String selection,
123 String[] selectionArgs, String sortOrder) {
124
125 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
126 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
127 qb.setTables(args.table);
128
Romain Guy73b979d2009-06-09 12:57:21 -0700129 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800130 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
131 result.setNotificationUri(getContext().getContentResolver(), uri);
132
133 return result;
134 }
135
Adam Cohen091440a2015-03-18 14:16:05 -0700136 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500138 if (values == null) {
139 throw new RuntimeException("Error: attempting to insert null values");
140 }
Adam Cohen71483f42014-05-15 14:04:01 -0700141 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700142 throw new RuntimeException("Error: attempting to add item without specifying an id");
143 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500144 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 return db.insert(table, nullColumnHack, values);
146 }
147
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800148 @Override
149 public Uri insert(Uri uri, ContentValues initialValues) {
150 SqlArguments args = new SqlArguments(uri);
151
Adam Cohena043fa82014-07-23 14:49:38 -0700152 // In very limited cases, we support system|signature permission apps to add to the db
153 String externalAdd = uri.getQueryParameter(URI_PARAM_IS_EXTERNAL_ADD);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700154 final boolean isExternalAll = externalAdd != null && "true".equals(externalAdd);
155 if (isExternalAll) {
Adam Cohena043fa82014-07-23 14:49:38 -0700156 if (!mOpenHelper.initializeExternalAdd(initialValues)) {
157 return null;
158 }
159 }
160
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800161 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400162 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700163 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800164 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165
166 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700167 notifyListeners();
168
169 if (isExternalAll) {
170 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
171 if (app != null) {
172 app.reloadWorkspace();
173 }
174 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175
176 return uri;
177 }
178
Adam Cohena043fa82014-07-23 14:49:38 -0700179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 @Override
181 public int bulkInsert(Uri uri, ContentValues[] values) {
182 SqlArguments args = new SqlArguments(uri);
183
184 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
185 db.beginTransaction();
186 try {
187 int numValues = values.length;
188 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400189 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700190 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
191 return 0;
192 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193 }
194 db.setTransactionSuccessful();
195 } finally {
196 db.endTransaction();
197 }
198
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700199 notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 return values.length;
201 }
202
203 @Override
Yura085c8532014-02-11 15:15:29 +0000204 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
205 throws OperationApplicationException {
206 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
207 db.beginTransaction();
208 try {
209 ContentProviderResult[] result = super.applyBatch(operations);
210 db.setTransactionSuccessful();
211 return result;
212 } finally {
213 db.endTransaction();
214 }
215 }
216
217 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218 public int delete(Uri uri, String selection, String[] selectionArgs) {
219 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
220
221 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
222 int count = db.delete(args.table, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700223 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224
225 return count;
226 }
227
228 @Override
229 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
230 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
231
Chris Wren1ada10d2013-09-13 18:01:38 -0400232 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
234 int count = db.update(args.table, values, 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
237 return count;
238 }
239
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700240 private void notifyListeners() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400241 // always notify the backup agent
Chris Wren92aa4232013-10-04 11:29:36 -0400242 LauncherBackupAgentHelper.dataChanged(getContext());
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700243 if (mListener != null) {
244 mListener.onLauncherProviderChange();
245 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400246 }
247
Adam Cohen091440a2015-03-18 14:16:05 -0700248 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400249 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800250 }
251
Adam Cohendcd297f2013-06-18 13:13:40 -0700252 public long generateNewItemId() {
253 return mOpenHelper.generateNewItemId();
254 }
255
Winson Chungc763c4e2013-07-19 13:49:06 -0700256 public void updateMaxItemId(long id) {
257 mOpenHelper.updateMaxItemId(id);
258 }
259
Adam Cohendcd297f2013-06-18 13:13:40 -0700260 public long generateNewScreenId() {
261 return mOpenHelper.generateNewScreenId();
262 }
263
Brian Muramatsu5524b492012-10-02 16:55:54 -0700264 /**
Sunny Goyal42de82f2014-09-26 22:09:29 -0700265 * Clears all the data for a fresh start.
266 */
267 synchronized public void createEmptyDB() {
268 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
269 }
270
Sunny Goyal33d44382014-10-16 09:24:19 -0700271 public void clearFlagEmptyDbCreated() {
272 String spKey = LauncherAppState.getSharedPreferencesKey();
273 getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE)
274 .edit()
275 .remove(EMPTY_DATABASE_CREATED)
276 .commit();
277 }
278
Sunny Goyal42de82f2014-09-26 22:09:29 -0700279 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700280 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700281 * 1) From the app restrictions
282 * 2) From a package provided by play store
283 * 3) From a partner configuration APK, already in the system image
284 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700285 */
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700286 synchronized public void loadDefaultFavoritesIfNecessary() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400287 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700288 SharedPreferences sp = getContext().getSharedPreferences(spKey, Context.MODE_PRIVATE);
Adam Cohene25af792013-06-06 23:08:25 -0700289
Winson Chungc763c4e2013-07-19 13:49:06 -0700290 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500291 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200292
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700293 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction();
294 if (loader == null) {
295 loader = AutoInstallsLayout.get(getContext(),
296 mOpenHelper.mAppWidgetHost, mOpenHelper);
297 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700298 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700299 final Partner partner = Partner.get(getContext().getPackageManager());
300 if (partner != null && partner.hasDefaultLayout()) {
301 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700302 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700303 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700304 if (workspaceResId != 0) {
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700305 loader = new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
306 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700307 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700308 }
309 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700310
Sunny Goyal9d219682014-10-23 14:21:02 -0700311 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700312 if (loader == null) {
Sunny Goyal9d219682014-10-23 14:21:02 -0700313 loader = getDefaultLayoutParser();
Brian Muramatsu5524b492012-10-02 16:55:54 -0700314 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800315
316 // There might be some partially restored DB items, due to buggy restore logic in
317 // previous versions of launcher.
318 createEmptyDB();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700319 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700320 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
321 && usingExternallyProvidedLayout) {
322 // Unable to load external layout. Cleanup and load the internal layout.
323 createEmptyDB();
324 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
325 getDefaultLayoutParser());
326 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700327 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700328 }
329 }
330
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700331 /**
332 * Creates workspace loader from an XML resource listed in the app restrictions.
333 *
334 * @return the loader if the restrictions are set and the resource exists; null otherwise.
335 */
336 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
337 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() {
338 // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18
339 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
340 return null;
341 }
342
343 Context ctx = getContext();
344 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
345 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700346 if (bundle == null) {
347 return null;
348 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700349
Sunny Goyal35ca8732015-04-06 10:45:31 -0700350 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700351 if (packageName != null) {
352 try {
353 Resources targetResources = ctx.getPackageManager()
354 .getResourcesForApplication(packageName);
355 return AutoInstallsLayout.get(ctx, packageName, targetResources,
356 mOpenHelper.mAppWidgetHost, mOpenHelper);
357 } catch (NameNotFoundException e) {
358 Log.e(TAG, "Target package for restricted profile not found", e);
359 return null;
360 }
361 }
362 return null;
363 }
364
Sunny Goyal9d219682014-10-23 14:21:02 -0700365 private DefaultLayoutParser getDefaultLayoutParser() {
366 int defaultLayout = LauncherAppState.getInstance()
367 .getDynamicGrid().getDeviceProfile().defaultLayoutId;
368 return new DefaultLayoutParser(getContext(), mOpenHelper.mAppWidgetHost,
369 mOpenHelper, getContext().getResources(), defaultLayout);
370 }
371
Dan Sandlerd5024042014-01-09 15:01:33 -0500372 public void migrateLauncher2Shortcuts() {
373 mOpenHelper.migrateLauncher2Shortcuts(mOpenHelper.getWritableDatabase(),
Jason Monk0bfcceb2014-03-21 15:42:06 -0400374 Uri.parse(getContext().getString(R.string.old_launcher_provider_uri)));
Dan Sandlerd5024042014-01-09 15:01:33 -0500375 }
376
Sunny Goyal08f72612015-01-05 13:41:43 -0800377 public void updateFolderItemsRank() {
378 mOpenHelper.updateFolderItemsRank(mOpenHelper.getWritableDatabase(), false);
379 }
380
Sunny Goyal5c97f512015-05-19 16:03:28 -0700381 public void convertShortcutsToLauncherActivities() {
382 mOpenHelper.convertShortcutsToLauncherActivities(mOpenHelper.getWritableDatabase());
383 }
384
385
Dan Sandlerd5024042014-01-09 15:01:33 -0500386 public void deleteDatabase() {
387 // Are you sure? (y/n)
388 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Dan Sandler2b471742014-01-21 14:14:41 -0500389 final File dbFile = new File(db.getPath());
Dan Sandlerd5024042014-01-09 15:01:33 -0500390 mOpenHelper.close();
Dan Sandler2b471742014-01-21 14:14:41 -0500391 if (dbFile.exists()) {
392 SQLiteDatabase.deleteDatabase(dbFile);
393 }
Dan Sandlerd5024042014-01-09 15:01:33 -0500394 mOpenHelper = new DatabaseHelper(getContext());
395 }
396
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700397 private static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800398 private final Context mContext;
Adam Cohen091440a2015-03-18 14:16:05 -0700399 @Thunk final AppWidgetHost mAppWidgetHost;
Adam Cohendcd297f2013-06-18 13:13:40 -0700400 private long mMaxItemId = -1;
401 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800402
Winson Chung0b560dd2014-01-21 13:00:26 -0800403 private boolean mNewDbCreated = false;
404
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800405 DatabaseHelper(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100406 super(context, LauncherFiles.LAUNCHER_DB, null, DATABASE_VERSION);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800407 mContext = context;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700408 mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
Winson Chung3d503fb2011-07-13 17:25:49 -0700409
410 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
411 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700412 if (mMaxItemId == -1) {
413 mMaxItemId = initializeMaxItemId(getWritableDatabase());
414 }
415 if (mMaxScreenId == -1) {
416 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700417 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800418 }
419
Winson Chung0b560dd2014-01-21 13:00:26 -0800420 public boolean wasNewDbCreated() {
421 return mNewDbCreated;
422 }
423
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700424 /**
425 * Send notification that we've deleted the {@link AppWidgetHost},
426 * probably as part of the initial database creation. The receiver may
427 * want to re-call {@link AppWidgetHost#startListening()} to ensure
428 * callbacks are correctly set.
429 */
430 private void sendAppWidgetResetNotify() {
431 final ContentResolver resolver = mContext.getContentResolver();
432 resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
433 }
434
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800435 @Override
436 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800437 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700438
Adam Cohendcd297f2013-06-18 13:13:40 -0700439 mMaxItemId = 1;
440 mMaxScreenId = 0;
Winson Chung0b560dd2014-01-21 13:00:26 -0800441 mNewDbCreated = true;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700442
Kenny Guyed131872014-04-30 03:02:21 +0100443 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
444 long userSerialNumber = userManager.getSerialNumberForUser(
445 UserHandleCompat.myUserHandle());
446
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800447 db.execSQL("CREATE TABLE favorites (" +
448 "_id INTEGER PRIMARY KEY," +
449 "title TEXT," +
450 "intent TEXT," +
451 "container INTEGER," +
452 "screen INTEGER," +
453 "cellX INTEGER," +
454 "cellY INTEGER," +
455 "spanX INTEGER," +
456 "spanY INTEGER," +
457 "itemType INTEGER," +
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700458 "appWidgetId INTEGER NOT NULL DEFAULT -1," +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800459 "isShortcut INTEGER," +
460 "iconType INTEGER," +
461 "iconPackage TEXT," +
462 "iconResource TEXT," +
463 "icon BLOB," +
464 "uri TEXT," +
Chris Wrend5e66bf2013-09-16 14:02:29 -0400465 "displayMode INTEGER," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400466 "appWidgetProvider TEXT," +
Chris Wrenf4d08112014-01-16 18:13:56 -0500467 "modified INTEGER NOT NULL DEFAULT 0," +
Kenny Guyed131872014-04-30 03:02:21 +0100468 "restored INTEGER NOT NULL DEFAULT 0," +
Sunny Goyal08f72612015-01-05 13:41:43 -0800469 "profileId INTEGER DEFAULT " + userSerialNumber + "," +
Sunny Goyal5d85c442015-03-10 13:14:47 -0700470 "rank INTEGER NOT NULL DEFAULT 0," +
471 "options INTEGER NOT NULL DEFAULT 0" +
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 ");");
Adam Cohendcd297f2013-06-18 13:13:40 -0700473 addWorkspacesTable(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800474
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700475 // Database was just created, so wipe any previous widgets
476 if (mAppWidgetHost != null) {
477 mAppWidgetHost.deleteHost();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700478 sendAppWidgetResetNotify();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800479 }
Winson Chung3d503fb2011-07-13 17:25:49 -0700480
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800481 // Fresh and clean launcher DB.
482 mMaxItemId = initializeMaxItemId(db);
483 setFlagEmptyDbCreated();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700484
485 // When a new DB is created, remove all previously stored managed profile information.
486 ManagedProfileHeuristic.processAllUsers(Collections.EMPTY_LIST, mContext);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800487 }
488
Adam Cohendcd297f2013-06-18 13:13:40 -0700489 private void addWorkspacesTable(SQLiteDatabase db) {
490 db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800491 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400492 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
493 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700494 ");");
495 }
496
Adam Cohen119285e2014-04-02 16:59:08 -0700497 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700498 // Delete items directly on the workspace who's screen id doesn't exist
499 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
500 // AND container = -100"
501 String removeOrphanedDesktopItems = "DELETE FROM " + TABLE_FAVORITES +
502 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700503 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700504 LauncherSettings.WorkspaceScreens._ID + " FROM " + TABLE_WORKSPACE_SCREENS + ")" +
505 " AND " +
506 LauncherSettings.Favorites.CONTAINER + " = " +
507 LauncherSettings.Favorites.CONTAINER_DESKTOP;
508 db.execSQL(removeOrphanedDesktopItems);
509
510 // Delete items contained in folders which no longer exist (after above statement)
511 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
512 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
513 String removeOrphanedFolderItems = "DELETE FROM " + TABLE_FAVORITES +
514 " WHERE " +
515 LauncherSettings.Favorites.CONTAINER + " <> " +
516 LauncherSettings.Favorites.CONTAINER_DESKTOP +
517 " AND "
518 + LauncherSettings.Favorites.CONTAINER + " <> " +
519 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
520 " AND "
521 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
522 LauncherSettings.Favorites._ID + " FROM " + TABLE_FAVORITES +
523 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
524 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
525 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700526 }
527
Winson Chungc763c4e2013-07-19 13:49:06 -0700528 private void setFlagJustLoadedOldDb() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400529 String spKey = LauncherAppState.getSharedPreferencesKey();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700530 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800531 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, false).commit();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700532 }
533
Winson Chungc763c4e2013-07-19 13:49:06 -0700534 private void setFlagEmptyDbCreated() {
535 String spKey = LauncherAppState.getSharedPreferencesKey();
536 SharedPreferences sp = mContext.getSharedPreferences(spKey, Context.MODE_PRIVATE);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800537 sp.edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Winson Chungc763c4e2013-07-19 13:49:06 -0700538 }
539
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 @Override
541 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700542 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800543 switch (oldVersion) {
544 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800545 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800546 case 12: {
547 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
548 // to persist workspace screens and their relative order.
549 mMaxScreenId = 0;
550 addWorkspacesTable(db);
551 }
552 case 13: {
553 db.beginTransaction();
554 try {
555 // Insert new column for holding widget provider name
556 db.execSQL("ALTER TABLE favorites " +
557 "ADD COLUMN appWidgetProvider TEXT;");
558 db.setTransactionSuccessful();
559 } catch (SQLException ex) {
560 Log.e(TAG, ex.getMessage(), ex);
561 // Old version remains, which means we wipe old data
562 break;
563 } finally {
564 db.endTransaction();
565 }
566 }
567 case 14: {
568 db.beginTransaction();
569 try {
570 // Insert new column for holding update timestamp
571 db.execSQL("ALTER TABLE favorites " +
572 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
573 db.execSQL("ALTER TABLE workspaceScreens " +
574 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
575 db.setTransactionSuccessful();
576 } catch (SQLException ex) {
577 Log.e(TAG, ex.getMessage(), ex);
578 // Old version remains, which means we wipe old data
579 break;
580 } finally {
581 db.endTransaction();
582 }
583 }
584 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700585 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800586 // Old version remains, which means we wipe old data
587 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800588 }
589 }
590 case 16: {
591 // We use the db version upgrade here to identify users who may not have seen
592 // clings yet (because they weren't available), but for whom the clings are now
593 // available (tablet users). Because one of the possible cling flows (migration)
594 // is very destructive (wipes out workspaces), we want to prevent this from showing
595 // until clear data. We do so by marking that the clings have been shown.
596 LauncherClings.synchonouslyMarkFirstRunClingDismissed(mContext);
597 }
598 case 17: {
599 // No-op
600 }
601 case 18: {
602 // Due to a data loss bug, some users may have items associated with screen ids
603 // which no longer exist. Since this can cause other problems, and since the user
604 // will never see these items anyway, we use database upgrade as an opportunity to
605 // clean things up.
606 removeOrphanedItems(db);
607 }
608 case 19: {
609 // Add userId column
610 if (!addProfileColumn(db)) {
611 // Old version remains, which means we wipe old data
612 break;
613 }
614 }
615 case 20:
616 if (!updateFolderItemsRank(db, true)) {
617 break;
618 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800619 case 21:
620 // Recreate workspace table with screen id a primary key
621 if (!recreateWorkspaceTable(db)) {
622 break;
623 }
624 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700625 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
626 // Old version remains, which means we wipe old data
627 break;
628 }
629 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700630 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700631 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700632 case 24:
633 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700634 case 25:
635 convertShortcutsToLauncherActivities(db);
636 case 26: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800637 // DB Upgraded successfully
638 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400639 }
640 }
641
Sunny Goyala2cc6242015-01-14 14:23:02 -0800642 // DB was not upgraded
643 Log.w(TAG, "Destroying all old data.");
644 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800646
Adam Cohen9b1d0622014-05-21 19:01:57 -0700647 @Override
648 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
649 // This shouldn't happen -- throw our hands up in the air and start over.
650 Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
651 ". Wiping databse.");
Sunny Goyal42de82f2014-09-26 22:09:29 -0700652 createEmptyDB(db);
653 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700654
Sunny Goyal42de82f2014-09-26 22:09:29 -0700655 /**
656 * Clears all the data for a fresh start.
657 */
658 public void createEmptyDB(SQLiteDatabase db) {
Adam Cohen9b1d0622014-05-21 19:01:57 -0700659 db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
660 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
661 onCreate(db);
662 }
663
Sunny Goyald2f38192015-02-25 10:46:34 -0800664 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700665 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
666 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
667 */
668 private void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
669 db.beginTransaction();
670 Cursor c = null;
671 SQLiteStatement updateStmt = null;
672
673 try {
674 // Only consider the primary user as other users can't have a shortcut.
675 long userSerial = UserManagerCompat.getInstance(mContext)
676 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
677 c = db.query(TABLE_FAVORITES, new String[] {
678 Favorites._ID,
679 Favorites.INTENT,
680 }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
681 null, null, null, null);
682
683 updateStmt = db.compileStatement("UPDATE favorites SET itemType="
684 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
685
686 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
687 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
688
689 while (c.moveToNext()) {
690 String intentDescription = c.getString(intentIndex);
691 Intent intent;
692 try {
693 intent = Intent.parseUri(intentDescription, 0);
694 } catch (URISyntaxException e) {
695 Log.e(TAG, "Unable to parse intent", e);
696 continue;
697 }
698
699 if (!InstallShortcutReceiver.isLauncherActivity(intent, mContext)) {
700 continue;
701 }
702
703 long id = c.getLong(idIndex);
704 updateStmt.bindLong(1, id);
705 updateStmt.execute();
706 }
707 db.setTransactionSuccessful();
708 } catch (SQLException ex) {
709 Log.w(TAG, "Error deduping shortcuts", ex);
710 } finally {
711 db.endTransaction();
712 if (c != null) {
713 c.close();
714 }
715 if (updateStmt != null) {
716 updateStmt.close();
717 }
718 }
719 }
720
721 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800722 * Recreates workspace table and migrates data to the new table.
723 */
724 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
725 db.beginTransaction();
726 try {
727 Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
728 new String[] {LauncherSettings.WorkspaceScreens._ID},
729 null, null, null, null,
730 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
731 ArrayList<Long> sortedIDs = new ArrayList<Long>();
732 long maxId = 0;
733 try {
734 while (c.moveToNext()) {
735 Long id = c.getLong(0);
736 if (!sortedIDs.contains(id)) {
737 sortedIDs.add(id);
738 maxId = Math.max(maxId, id);
739 }
740 }
741 } finally {
742 c.close();
743 }
744
745 db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
746 addWorkspacesTable(db);
747
748 // Add all screen ids back
749 int total = sortedIDs.size();
750 for (int i = 0; i < total; i++) {
751 ContentValues values = new ContentValues();
752 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
753 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
754 addModifiedTime(values);
755 db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
756 }
757 db.setTransactionSuccessful();
758 mMaxScreenId = maxId;
759 } catch (SQLException ex) {
760 // Old version remains, which means we wipe old data
761 Log.e(TAG, ex.getMessage(), ex);
762 return false;
763 } finally {
764 db.endTransaction();
765 }
766 return true;
767 }
768
Adam Cohen091440a2015-03-18 14:16:05 -0700769 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800770 db.beginTransaction();
771 try {
772 if (addRankColumn) {
773 // Insert new column for holding rank
774 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
775 }
776
777 // Get a map for folder ID to folder width
778 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
779 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
780 + " GROUP BY container;",
781 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
782
783 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800784 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
785 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800786 new Object[] {c.getLong(1) + 1, c.getLong(0)});
787 }
788
789 c.close();
790 db.setTransactionSuccessful();
791 } catch (SQLException ex) {
792 // Old version remains, which means we wipe old data
793 Log.e(TAG, ex.getMessage(), ex);
794 return false;
795 } finally {
796 db.endTransaction();
797 }
798 return true;
799 }
800
Kenny Guyed131872014-04-30 03:02:21 +0100801 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700802 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
803 // Default to the serial number of this user, for older
804 // shortcuts.
805 long userSerialNumber = userManager.getSerialNumberForUser(
806 UserHandleCompat.myUserHandle());
807 return addIntegerColumn(db, Favorites.PROFILE_ID, userSerialNumber);
808 }
809
810 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Kenny Guyed131872014-04-30 03:02:21 +0100811 db.beginTransaction();
812 try {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700813 db.execSQL("ALTER TABLE favorites ADD COLUMN "
814 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Kenny Guyed131872014-04-30 03:02:21 +0100815 db.setTransactionSuccessful();
816 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100817 Log.e(TAG, ex.getMessage(), ex);
818 return false;
819 } finally {
820 db.endTransaction();
821 }
822 return true;
823 }
824
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700825 // Generates a new ID to use for an object in your database. This method should be only
826 // called from the main UI thread. As an exception, we do call it when we call the
827 // constructor from the worker thread; however, this doesn't extend until after the
828 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
829 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700830 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -0700831 public long generateNewItemId() {
832 if (mMaxItemId < 0) {
833 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700834 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700835 mMaxItemId += 1;
836 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700837 }
838
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700839 @Override
840 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
841 return dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
842 }
843
Winson Chungc763c4e2013-07-19 13:49:06 -0700844 public void updateMaxItemId(long id) {
845 mMaxItemId = id + 1;
846 }
847
Chris Wren5dee7af2013-12-20 17:22:11 -0500848 public void checkId(String table, ContentValues values) {
849 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
850 if (table == LauncherProvider.TABLE_WORKSPACE_SCREENS) {
851 mMaxScreenId = Math.max(id, mMaxScreenId);
852 } else {
853 mMaxItemId = Math.max(id, mMaxItemId);
854 }
855 }
856
Adam Cohendcd297f2013-06-18 13:13:40 -0700857 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800858 return getMaxId(db, TABLE_FAVORITES);
Adam Cohendcd297f2013-06-18 13:13:40 -0700859 }
860
861 // Generates a new ID to use for an workspace screen in your database. This method
862 // should be only called from the main UI thread. As an exception, we do call it when we
863 // call the constructor from the worker thread; however, this doesn't extend until after the
864 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
865 // after that point
866 public long generateNewScreenId() {
867 if (mMaxScreenId < 0) {
868 throw new RuntimeException("Error: max screen id was not initialized");
869 }
870 mMaxScreenId += 1;
Winson Chunga90303b2013-11-15 13:05:06 -0800871 // Log to disk
872 Launcher.addDumpLog(TAG, "11683562 - generateNewScreenId(): " + mMaxScreenId, true);
Adam Cohendcd297f2013-06-18 13:13:40 -0700873 return mMaxScreenId;
874 }
875
Adam Cohendcd297f2013-06-18 13:13:40 -0700876 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800877 return getMaxId(db, TABLE_WORKSPACE_SCREENS);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800878 }
879
Adam Cohen091440a2015-03-18 14:16:05 -0700880 @Thunk boolean initializeExternalAdd(ContentValues values) {
Adam Cohena043fa82014-07-23 14:49:38 -0700881 // 1. Ensure that externally added items have a valid item id
882 long id = generateNewItemId();
883 values.put(LauncherSettings.Favorites._ID, id);
884
885 // 2. In the case of an app widget, and if no app widget id is specified, we
886 // attempt allocate and bind the widget.
887 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
888 if (itemType != null &&
889 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
890 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
891
892 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
893 ComponentName cn = ComponentName.unflattenFromString(
894 values.getAsString(Favorites.APPWIDGET_PROVIDER));
895
896 if (cn != null) {
897 try {
898 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Adam Cohen3ed316a2014-07-23 18:21:20 -0700899 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
Adam Coheneb1ac422014-10-14 08:55:28 -0700900 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Adam Cohend61a6382014-10-14 15:04:34 -0700901 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700902 }
903 } catch (RuntimeException e) {
904 Log.e(TAG, "Failed to initialize external widget", e);
Adam Coheneb1ac422014-10-14 08:55:28 -0700905 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700906 }
Adam Coheneb1ac422014-10-14 08:55:28 -0700907 } else {
908 return false;
Adam Cohena043fa82014-07-23 14:49:38 -0700909 }
910 }
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700911
912 // Add screen id if not present
913 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
914 if (!addScreenIdIfNecessary(screenId)) {
915 return false;
916 }
Adam Cohena043fa82014-07-23 14:49:38 -0700917 return true;
918 }
919
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700920 // Returns true of screen id exists, or if successfully added
921 private boolean addScreenIdIfNecessary(long screenId) {
922 if (!hasScreenId(screenId)) {
923 int rank = getMaxScreenRank() + 1;
924
925 ContentValues v = new ContentValues();
926 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
927 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
928 if (dbInsertAndCheck(this, getWritableDatabase(),
929 TABLE_WORKSPACE_SCREENS, null, v) < 0) {
930 return false;
931 }
932 }
933 return true;
934 }
935
936 private boolean hasScreenId(long screenId) {
937 SQLiteDatabase db = getWritableDatabase();
938 Cursor c = db.rawQuery("SELECT * FROM " + TABLE_WORKSPACE_SCREENS + " WHERE "
939 + LauncherSettings.WorkspaceScreens._ID + " = " + screenId, null);
940 if (c != null) {
941 int count = c.getCount();
942 c.close();
943 return count > 0;
944 } else {
945 return false;
946 }
947 }
948
949 private int getMaxScreenRank() {
950 SQLiteDatabase db = getWritableDatabase();
951 Cursor c = db.rawQuery("SELECT MAX(" + LauncherSettings.WorkspaceScreens.SCREEN_RANK
952 + ") FROM " + TABLE_WORKSPACE_SCREENS, null);
953
954 // get the result
955 final int maxRankIndex = 0;
956 int rank = -1;
957 if (c != null && c.moveToNext()) {
958 rank = c.getInt(maxRankIndex);
959 }
960 if (c != null) {
961 c.close();
962 }
963
964 return rank;
965 }
966
Adam Cohen091440a2015-03-18 14:16:05 -0700967 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -0700968 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700969 // TODO: Use multiple loaders with fall-back and transaction.
970 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -0700971
972 // Add the screens specified by the items above
973 Collections.sort(screenIds);
974 int rank = 0;
975 ContentValues values = new ContentValues();
976 for (Long id : screenIds) {
977 values.clear();
978 values.put(LauncherSettings.WorkspaceScreens._ID, id);
979 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
980 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values) < 0) {
981 throw new RuntimeException("Failed initialize screen table"
982 + "from default layout");
983 }
984 rank++;
985 }
986
987 // Ensure that the max ids are initialized
988 mMaxItemId = initializeMaxItemId(db);
989 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700990
Adam Cohen71483f42014-05-15 14:04:01 -0700991 return count;
992 }
993
Adam Cohen091440a2015-03-18 14:16:05 -0700994 @Thunk void migrateLauncher2Shortcuts(SQLiteDatabase db, Uri uri) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500995 final ContentResolver resolver = mContext.getContentResolver();
996 Cursor c = null;
997 int count = 0;
998 int curScreen = 0;
999
1000 try {
1001 c = resolver.query(uri, null, null, null, "title ASC");
1002 } catch (Exception e) {
1003 // Ignore
1004 }
1005
Dan Sandlerd5024042014-01-09 15:01:33 -05001006 // We already have a favorites database in the old provider
1007 if (c != null) {
1008 try {
1009 if (c.getCount() > 0) {
1010 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1011 final int intentIndex
1012 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1013 final int titleIndex
1014 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1015 final int iconTypeIndex
1016 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
1017 final int iconIndex
1018 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1019 final int iconPackageIndex
1020 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
1021 final int iconResourceIndex
1022 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
1023 final int containerIndex
1024 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
1025 final int itemTypeIndex
1026 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1027 final int screenIndex
1028 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
1029 final int cellXIndex
1030 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
1031 final int cellYIndex
1032 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
1033 final int uriIndex
1034 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1035 final int displayModeIndex
1036 = c.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
Kenny Guyed131872014-04-30 03:02:21 +01001037 final int profileIndex
1038 = c.getColumnIndex(LauncherSettings.Favorites.PROFILE_ID);
Dan Sandlerd5024042014-01-09 15:01:33 -05001039
1040 int i = 0;
1041 int curX = 0;
1042 int curY = 0;
1043
1044 final LauncherAppState app = LauncherAppState.getInstance();
1045 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1046 final int width = (int) grid.numColumns;
1047 final int height = (int) grid.numRows;
1048 final int hotseatWidth = (int) grid.numHotseatIcons;
1049
1050 final HashSet<String> seenIntents = new HashSet<String>(c.getCount());
1051
Adam Cohen72960972014-01-15 18:13:55 -08001052 final ArrayList<ContentValues> shortcuts = new ArrayList<ContentValues>();
1053 final ArrayList<ContentValues> folders = new ArrayList<ContentValues>();
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001054 final SparseArray<ContentValues> hotseat = new SparseArray<ContentValues>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001055
1056 while (c.moveToNext()) {
1057 final int itemType = c.getInt(itemTypeIndex);
1058 if (itemType != Favorites.ITEM_TYPE_APPLICATION
1059 && itemType != Favorites.ITEM_TYPE_SHORTCUT
1060 && itemType != Favorites.ITEM_TYPE_FOLDER) {
1061 continue;
1062 }
1063
1064 final int cellX = c.getInt(cellXIndex);
1065 final int cellY = c.getInt(cellYIndex);
1066 final int screen = c.getInt(screenIndex);
1067 int container = c.getInt(containerIndex);
1068 final String intentStr = c.getString(intentIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001069
1070 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
1071 UserHandleCompat userHandle;
1072 final long userSerialNumber;
1073 if (profileIndex != -1 && !c.isNull(profileIndex)) {
1074 userSerialNumber = c.getInt(profileIndex);
1075 userHandle = userManager.getUserForSerialNumber(userSerialNumber);
1076 } else {
1077 // Default to the serial number of this user, for older
1078 // shortcuts.
1079 userHandle = UserHandleCompat.myUserHandle();
1080 userSerialNumber = userManager.getSerialNumberForUser(userHandle);
1081 }
Sunny Goyal416541c2014-11-14 11:59:57 -08001082
1083 if (userHandle == null) {
1084 Launcher.addDumpLog(TAG, "skipping deleted user", true);
1085 continue;
1086 }
1087
Dan Sandlerd5024042014-01-09 15:01:33 -05001088 Launcher.addDumpLog(TAG, "migrating \""
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001089 + c.getString(titleIndex) + "\" ("
1090 + cellX + "," + cellY + "@"
1091 + LauncherSettings.Favorites.containerToString(container)
1092 + "/" + screen
1093 + "): " + intentStr, true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001094
1095 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
Adam Cohen556f6132014-01-15 15:18:08 -08001096
1097 final Intent intent;
1098 final ComponentName cn;
1099 try {
1100 intent = Intent.parseUri(intentStr, 0);
1101 } catch (URISyntaxException e) {
1102 // bogus intent?
1103 Launcher.addDumpLog(TAG,
1104 "skipping invalid intent uri", true);
1105 continue;
1106 }
1107
1108 cn = intent.getComponent();
Dan Sandlerd5024042014-01-09 15:01:33 -05001109 if (TextUtils.isEmpty(intentStr)) {
1110 // no intent? no icon
1111 Launcher.addDumpLog(TAG, "skipping empty intent", true);
1112 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001113 } else if (cn != null &&
Kenny Guyed131872014-04-30 03:02:21 +01001114 !LauncherModel.isValidPackageActivity(mContext, cn,
1115 userHandle)) {
Adam Cohen556f6132014-01-15 15:18:08 -08001116 // component no longer exists.
Adam Cohen72960972014-01-15 18:13:55 -08001117 Launcher.addDumpLog(TAG, "skipping item whose component " +
Adam Cohen556f6132014-01-15 15:18:08 -08001118 "no longer exists.", true);
1119 continue;
Adam Cohen72960972014-01-15 18:13:55 -08001120 } else if (container ==
1121 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1122 // Dedupe icons directly on the workspace
1123
Adam Cohen556f6132014-01-15 15:18:08 -08001124 // Canonicalize
1125 // the Play Store sets the package parameter, but Launcher
Adam Cohena33f11e2014-10-24 12:20:20 -07001126 // does not, so we clear that out to keep them the same.
1127 // Also ignore intent flags for the purposes of deduping.
Adam Cohen556f6132014-01-15 15:18:08 -08001128 intent.setPackage(null);
Adam Cohena33f11e2014-10-24 12:20:20 -07001129 int flags = intent.getFlags();
1130 intent.setFlags(0);
Adam Cohen556f6132014-01-15 15:18:08 -08001131 final String key = intent.toUri(0);
Adam Cohena33f11e2014-10-24 12:20:20 -07001132 intent.setFlags(flags);
Adam Cohen556f6132014-01-15 15:18:08 -08001133 if (seenIntents.contains(key)) {
1134 Launcher.addDumpLog(TAG, "skipping duplicate", true);
Dan Sandlerd5024042014-01-09 15:01:33 -05001135 continue;
Adam Cohen556f6132014-01-15 15:18:08 -08001136 } else {
1137 seenIntents.add(key);
Dan Sandlerd5024042014-01-09 15:01:33 -05001138 }
1139 }
1140 }
1141
1142 ContentValues values = new ContentValues(c.getColumnCount());
1143 values.put(LauncherSettings.Favorites._ID, c.getInt(idIndex));
1144 values.put(LauncherSettings.Favorites.INTENT, intentStr);
1145 values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
1146 values.put(LauncherSettings.Favorites.ICON_TYPE,
1147 c.getInt(iconTypeIndex));
1148 values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
1149 values.put(LauncherSettings.Favorites.ICON_PACKAGE,
1150 c.getString(iconPackageIndex));
1151 values.put(LauncherSettings.Favorites.ICON_RESOURCE,
1152 c.getString(iconResourceIndex));
1153 values.put(LauncherSettings.Favorites.ITEM_TYPE, itemType);
1154 values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
1155 values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
1156 values.put(LauncherSettings.Favorites.DISPLAY_MODE,
1157 c.getInt(displayModeIndex));
Kenny Guyed131872014-04-30 03:02:21 +01001158 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
Dan Sandlerd5024042014-01-09 15:01:33 -05001159
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001160 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1161 hotseat.put(screen, values);
Dan Sandlerd5024042014-01-09 15:01:33 -05001162 }
1163
1164 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1165 // In a folder or in the hotseat, preserve position
1166 values.put(LauncherSettings.Favorites.SCREEN, screen);
1167 values.put(LauncherSettings.Favorites.CELLX, cellX);
1168 values.put(LauncherSettings.Favorites.CELLY, cellY);
1169 } else {
Adam Cohen72960972014-01-15 18:13:55 -08001170 // For items contained directly on one of the workspace screen,
1171 // we'll determine their location (screen, x, y) in a second pass.
Dan Sandlerd5024042014-01-09 15:01:33 -05001172 }
1173
1174 values.put(LauncherSettings.Favorites.CONTAINER, container);
1175
Adam Cohen72960972014-01-15 18:13:55 -08001176 if (itemType != Favorites.ITEM_TYPE_FOLDER) {
1177 shortcuts.add(values);
1178 } else {
1179 folders.add(values);
1180 }
Dan Sandlerd5024042014-01-09 15:01:33 -05001181 }
1182
Dan Sandlerab5fa3a2014-03-06 23:48:04 -05001183 // Now that we have all the hotseat icons, let's go through them left-right
1184 // and assign valid locations for them in the new hotseat
1185 final int N = hotseat.size();
1186 for (int idx=0; idx<N; idx++) {
1187 int hotseatX = hotseat.keyAt(idx);
1188 ContentValues values = hotseat.valueAt(idx);
1189
1190 if (hotseatX == grid.hotseatAllAppsRank) {
1191 // let's drop this in the next available hole in the hotseat
1192 while (++hotseatX < hotseatWidth) {
1193 if (hotseat.get(hotseatX) == null) {
1194 // found a spot! move it here
1195 values.put(LauncherSettings.Favorites.SCREEN,
1196 hotseatX);
1197 break;
1198 }
1199 }
1200 }
1201 if (hotseatX >= hotseatWidth) {
1202 // no room for you in the hotseat? it's off to the desktop with you
1203 values.put(LauncherSettings.Favorites.CONTAINER,
1204 Favorites.CONTAINER_DESKTOP);
1205 }
1206 }
1207
Adam Cohen72960972014-01-15 18:13:55 -08001208 final ArrayList<ContentValues> allItems = new ArrayList<ContentValues>();
1209 // Folders first
1210 allItems.addAll(folders);
1211 // Then shortcuts
1212 allItems.addAll(shortcuts);
1213
1214 // Layout all the folders
1215 for (ContentValues values: allItems) {
1216 if (values.getAsInteger(LauncherSettings.Favorites.CONTAINER) !=
1217 LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1218 // Hotseat items and folder items have already had their
1219 // location information set. Nothing to be done here.
1220 continue;
1221 }
1222 values.put(LauncherSettings.Favorites.SCREEN, curScreen);
1223 values.put(LauncherSettings.Favorites.CELLX, curX);
1224 values.put(LauncherSettings.Favorites.CELLY, curY);
1225 curX = (curX + 1) % width;
1226 if (curX == 0) {
1227 curY = (curY + 1);
1228 }
1229 // Leave the last row of icons blank on every screen
1230 if (curY == height - 1) {
1231 curScreen = (int) generateNewScreenId();
1232 curY = 0;
1233 }
1234 }
1235
1236 if (allItems.size() > 0) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001237 db.beginTransaction();
1238 try {
Adam Cohen72960972014-01-15 18:13:55 -08001239 for (ContentValues row: allItems) {
1240 if (row == null) continue;
1241 if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, row)
Dan Sandlerd5024042014-01-09 15:01:33 -05001242 < 0) {
1243 return;
1244 } else {
1245 count++;
1246 }
1247 }
1248 db.setTransactionSuccessful();
1249 } finally {
1250 db.endTransaction();
1251 }
1252 }
1253
1254 db.beginTransaction();
1255 try {
1256 for (i=0; i<=curScreen; i++) {
1257 final ContentValues values = new ContentValues();
1258 values.put(LauncherSettings.WorkspaceScreens._ID, i);
1259 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
1260 if (dbInsertAndCheck(this, db, TABLE_WORKSPACE_SCREENS, null, values)
1261 < 0) {
1262 return;
1263 }
1264 }
1265 db.setTransactionSuccessful();
1266 } finally {
1267 db.endTransaction();
1268 }
Sunny Goyal08f72612015-01-05 13:41:43 -08001269
1270 updateFolderItemsRank(db, false);
Dan Sandlerd5024042014-01-09 15:01:33 -05001271 }
1272 } finally {
1273 c.close();
1274 }
1275 }
1276
1277 Launcher.addDumpLog(TAG, "migrated " + count + " icons from Launcher2 into "
1278 + (curScreen+1) + " screens", true);
1279
1280 // ensure that new screens are created to hold these icons
1281 setFlagJustLoadedOldDb();
1282
1283 // Update max IDs; very important since we just grabbed IDs from another database
1284 mMaxItemId = initializeMaxItemId(db);
1285 mMaxScreenId = initializeMaxScreenId(db);
1286 if (LOGD) Log.d(TAG, "mMaxItemId: " + mMaxItemId + " mMaxScreenId: " + mMaxScreenId);
1287 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001288 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001289
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001290 /**
1291 * @return the max _id in the provided table.
1292 */
Adam Cohen091440a2015-03-18 14:16:05 -07001293 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001294 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1295 // get the result
1296 long id = -1;
1297 if (c != null && c.moveToNext()) {
1298 id = c.getLong(0);
1299 }
1300 if (c != null) {
1301 c.close();
1302 }
1303
1304 if (id == -1) {
1305 throw new RuntimeException("Error: could not query max id in " + table);
1306 }
1307
1308 return id;
1309 }
1310
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001311 static class SqlArguments {
1312 public final String table;
1313 public final String where;
1314 public final String[] args;
1315
1316 SqlArguments(Uri url, String where, String[] args) {
1317 if (url.getPathSegments().size() == 1) {
1318 this.table = url.getPathSegments().get(0);
1319 this.where = where;
1320 this.args = args;
1321 } else if (url.getPathSegments().size() != 2) {
1322 throw new IllegalArgumentException("Invalid URI: " + url);
1323 } else if (!TextUtils.isEmpty(where)) {
1324 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1325 } else {
1326 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001327 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001328 this.args = null;
1329 }
1330 }
1331
1332 SqlArguments(Uri url) {
1333 if (url.getPathSegments().size() == 1) {
1334 table = url.getPathSegments().get(0);
1335 where = null;
1336 args = null;
1337 } else {
1338 throw new IllegalArgumentException("Invalid URI: " + url);
1339 }
1340 }
1341 }
Adam Cohen72960972014-01-15 18:13:55 -08001342}