ConversationCursor.java revision 1c3911727b435524e7d4d0cc66ad3522adbd3453
1/******************************************************************************* 2 * Copyright (C) 2012 Google Inc. 3 * Licensed to The Android Open Source Project. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 *******************************************************************************/ 17 18package com.android.mail.browse; 19 20import android.app.Activity; 21import android.content.ContentProvider; 22import android.content.ContentProviderOperation; 23import android.content.ContentResolver; 24import android.content.ContentValues; 25import android.content.Context; 26import android.content.OperationApplicationException; 27import android.database.CharArrayBuffer; 28import android.database.ContentObserver; 29import android.database.Cursor; 30import android.database.CursorWrapper; 31import android.database.DataSetObservable; 32import android.database.DataSetObserver; 33import android.net.Uri; 34import android.os.AsyncTask; 35import android.os.Bundle; 36import android.os.Looper; 37import android.os.RemoteException; 38 39import com.android.mail.providers.Conversation; 40import com.android.mail.providers.UIProvider; 41import com.android.mail.providers.UIProvider.ConversationColumns; 42import com.android.mail.providers.UIProvider.ConversationListQueryParameters; 43import com.android.mail.providers.UIProvider.ConversationOperations; 44import com.android.mail.utils.LogUtils; 45import com.google.common.annotations.VisibleForTesting; 46import com.google.common.collect.Lists; 47 48import java.util.ArrayList; 49import java.util.Arrays; 50import java.util.Collection; 51import java.util.HashMap; 52import java.util.Iterator; 53import java.util.List; 54 55/** 56 * ConversationCursor is a wrapper around a conversation list cursor that provides update/delete 57 * caching for quick UI response. This is effectively a singleton class, as the cache is 58 * implemented as a static HashMap. 59 */ 60public final class ConversationCursor implements Cursor { 61 private static final String TAG = "ConversationCursor"; 62 63 private static final boolean DEBUG = true; // STOPSHIP Set to false before shipping 64 // A deleted row is indicated by the presence of DELETED_COLUMN in the cache map 65 private static final String DELETED_COLUMN = "__deleted__"; 66 // An row cached during a requery is indicated by the presence of REQUERY_COLUMN in the map 67 private static final String REQUERY_COLUMN = "__requery__"; 68 // A sentinel value for the "index" of the deleted column; it's an int that is otherwise invalid 69 private static final int DELETED_COLUMN_INDEX = -1; 70 // Empty deletion list 71 private static final ArrayList<Integer> EMPTY_DELETION_LIST = Lists.newArrayList(); 72 // The index of the Uri whose data is reflected in the cached row 73 // Updates/Deletes to this Uri are cached 74 private static int sUriColumnIndex; 75 // Our sequence count (for changes sent to underlying provider) 76 private static int sSequence = 0; 77 // The resolver for the cursor instantiator's context 78 private static ContentResolver sResolver; 79 @VisibleForTesting 80 static ConversationProvider sProvider; 81 82 // The cursor instantiator's activity 83 private Activity mActivity; 84 // The cursor underlying the caching cursor 85 @VisibleForTesting 86 Wrapper mUnderlyingCursor; 87 // The new cursor obtained via a requery 88 private volatile Wrapper mRequeryCursor; 89 // A mapping from Uri to updated ContentValues 90 private HashMap<String, ContentValues> mCacheMap = new HashMap<String, ContentValues>(); 91 // Cache map lock (will be used only very briefly - few ms at most) 92 private Object mCacheMapLock = new Object(); 93 // The listeners registered for this cursor 94 private List<ConversationListener> mListeners = Lists.newArrayList(); 95 // The ConversationProvider instance 96 // The runnable executing a refresh (query of underlying provider) 97 private RefreshTask mRefreshTask; 98 // Set when we've sent refreshReady() to listeners 99 private boolean mRefreshReady = false; 100 // Set when we've sent refreshRequired() to listeners 101 private boolean mRefreshRequired = false; 102 // Whether our first query on this cursor should include a limit 103 private boolean mInitialConversationLimit = false; 104 // A list of mostly-dead items 105 private List<Conversation> sMostlyDead = Lists.newArrayList(); 106 // The name of the loader 107 private final String mName; 108 // Column names for this cursor 109 private String[] mColumnNames; 110 // An observer on the underlying cursor (so we can detect changes from outside the UI) 111 private final CursorObserver mCursorObserver; 112 // Whether our observer is currently registered with the underlying cursor 113 private boolean mCursorObserverRegistered = false; 114 // Whether our loader is paused 115 private boolean mPaused = false; 116 // Whether or not sync from underlying provider should be deferred 117 private boolean mDeferSync = false; 118 119 // The current position of the cursor 120 private int mPosition = -1; 121 122 /** 123 * Allow UI elements to subscribe to changes that other UI elements might make to this data. 124 * This short circuits the usual DB round-trip needed for data to propagate across disparate 125 * UI elements. 126 * <p> 127 * A UI element that receives a notification on this channel should just update its existing 128 * view, and should not trigger a full refresh. 129 */ 130 private final DataSetObservable mDataSetObservable = new DataSetObservable(); 131 132 // The number of cached deletions from this cursor (used to quickly generate an accurate count) 133 private int mDeletedCount = 0; 134 135 // Parameters passed to the underlying query 136 private Uri qUri; 137 private String[] qProjection; 138 139 private void setCursor(Wrapper cursor) { 140 // If we have an existing underlying cursor, make sure it's closed 141 if (mUnderlyingCursor != null) { 142 mUnderlyingCursor.close(); 143 } 144 mColumnNames = cursor.getColumnNames(); 145 mRefreshRequired = false; 146 mRefreshReady = false; 147 mRefreshTask = null; 148 resetCursor(cursor); 149 } 150 151 public ConversationCursor(Activity activity, Uri uri, boolean initialConversationLimit, 152 String name) { 153 //sActivity = activity; 154 mInitialConversationLimit = initialConversationLimit; 155 sResolver = activity.getContentResolver(); 156 sUriColumnIndex = UIProvider.CONVERSATION_URI_COLUMN; 157 qUri = uri; 158 mName = name; 159 qProjection = UIProvider.CONVERSATION_PROJECTION; 160 mCursorObserver = new CursorObserver(); 161 } 162 163 /** 164 * Create a ConversationCursor; this should be called by the ListActivity using that cursor 165 * @param activity the activity creating the cursor 166 * @param messageListColumn the column used for individual cursor items 167 * @param uri the query uri 168 * @param projection the query projecion 169 * @param selection the query selection 170 * @param selectionArgs the query selection args 171 * @param sortOrder the query sort order 172 * @return a ConversationCursor 173 */ 174 public void load() { 175 synchronized (mCacheMapLock) { 176 try { 177 // Create new ConversationCursor 178 LogUtils.i(TAG, "Create: initial creation"); 179 Wrapper c = doQuery(mInitialConversationLimit); 180 setCursor(c); 181 } finally { 182 // If we used a limit, queue up a query without limit 183 if (mInitialConversationLimit) { 184 mInitialConversationLimit = false; 185 refresh(); 186 } 187 } 188 } 189 } 190 191 /** 192 * Pause notifications to UI 193 */ 194 public void pause() { 195 if (DEBUG) { 196 LogUtils.i(TAG, "[Paused: " + mName + "]"); 197 } 198 mPaused = true; 199 } 200 201 /** 202 * Resume notifications to UI; if any are pending, send them 203 */ 204 public void resume() { 205 if (DEBUG) { 206 LogUtils.i(TAG, "[Resumed: " + mName + "]"); 207 } 208 mPaused = false; 209 checkNotifyUI(); 210 } 211 212 private void checkNotifyUI() { 213 if (!mPaused && !mDeferSync) { 214 if (mRefreshRequired && (mRefreshTask == null)) { 215 notifyRefreshRequired(); 216 } else if (mRefreshReady) { 217 notifyRefreshReady(); 218 } 219 } else { 220 LogUtils.i(TAG, "[checkNotifyUI: " + (mPaused ? "Paused " : "") + 221 (mDeferSync ? "Defer" : "")); 222 } 223 } 224 225 /** 226 * Runnable that performs the query on the underlying provider 227 */ 228 private class RefreshTask extends AsyncTask<Void, Void, Void> { 229 private Wrapper mCursor = null; 230 231 private RefreshTask() { 232 } 233 234 @Override 235 protected Void doInBackground(Void... params) { 236 if (DEBUG) { 237 LogUtils.i(TAG, "[Start refresh of " + mName + ": %d]", hashCode()); 238 } 239 // Get new data 240 mCursor = doQuery(false); 241 return null; 242 } 243 244 @Override 245 protected void onPostExecute(Void param) { 246 synchronized(mCacheMapLock) { 247 mRequeryCursor = mCursor; 248 // Make sure window is full 249 mRequeryCursor.getCount(); 250 mRefreshReady = true; 251 if (DEBUG) { 252 LogUtils.i(TAG, "[Query done " + mName + ": %d]", hashCode()); 253 } 254 if (!mDeferSync && !mPaused) { 255 notifyRefreshReady(); 256 } 257 } 258 } 259 260 @Override 261 protected void onCancelled() { 262 if (DEBUG) { 263 LogUtils.i(TAG, "[Ignoring refresh result: %d]", hashCode()); 264 } 265 if (mCursor != null) { 266 mCursor.close(); 267 } 268 } 269 } 270 271 /** 272 * Wrapper that includes the Uri used to create the cursor 273 */ 274 private static class Wrapper extends CursorWrapper { 275 private final Uri mUri; 276 277 Wrapper(Cursor cursor, Uri uri) { 278 super(cursor); 279 mUri = uri; 280 } 281 } 282 283 private Wrapper doQuery(boolean withLimit) { 284 if (sResolver == null) { 285 sResolver = mActivity.getContentResolver(); 286 } 287 Uri uri = qUri; 288 if (withLimit) { 289 uri = uri.buildUpon().appendQueryParameter(ConversationListQueryParameters.LIMIT, 290 ConversationListQueryParameters.DEFAULT_LIMIT).build(); 291 } 292 long time = System.currentTimeMillis(); 293 294 Wrapper result = new Wrapper(sResolver.query(uri, qProjection, null, null, null), uri); 295 if (DEBUG) { 296 time = System.currentTimeMillis() - time; 297 LogUtils.i(TAG, "ConversationCursor query: %s, %dms, %d results", 298 uri, time, result.getCount()); 299 } 300 return result; 301 } 302 303 /** 304 * Return whether the uri string (message list uri) is in the underlying cursor 305 * @param uriString the uri string we're looking for 306 * @return true if the uri string is in the cursor; false otherwise 307 */ 308 private boolean isInUnderlyingCursor(String uriString) { 309 mUnderlyingCursor.moveToPosition(-1); 310 while (mUnderlyingCursor.moveToNext()) { 311 if (uriString.equals(mUnderlyingCursor.getString(sUriColumnIndex))) { 312 return true; 313 } 314 } 315 return false; 316 } 317 318 static boolean offUiThread() { 319 return Looper.getMainLooper().getThread() != Thread.currentThread(); 320 } 321 322 /** 323 * Reset the cursor; this involves clearing out our cache map and resetting our various counts 324 * The cursor should be reset whenever we get fresh data from the underlying cursor. The cache 325 * is locked during the reset, which will block the UI, but for only a very short time 326 * (estimated at a few ms, but we can profile this; remember that the cache will usually 327 * be empty or have a few entries) 328 */ 329 private void resetCursor(Wrapper newCursor) { 330 synchronized (mCacheMapLock) { 331 // Walk through the cache. Here are the cases: 332 // 1) The entry isn't marked with REQUERY - remove it from the cache. If DELETED is 333 // set, decrement the deleted count 334 // 2) The REQUERY entry is still in the UP 335 // 2a) The REQUERY entry isn't DELETED; we're good, and the client change will remain 336 // (i.e. client wins, it's on its way to the UP) 337 // 2b) The REQUERY entry is DELETED; we're good (client change remains, it's on 338 // its way to the UP) 339 // 3) the REQUERY was deleted on the server (sheesh; this would be bizarre timing!) - 340 // we need to throw the item out of the cache 341 // So ... the only interesting case is #3, we need to look for remaining deleted items 342 // and see if they're still in the UP 343 Iterator<HashMap.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator(); 344 while (iter.hasNext()) { 345 HashMap.Entry<String, ContentValues> entry = iter.next(); 346 ContentValues values = entry.getValue(); 347 if (values.containsKey(REQUERY_COLUMN) && isInUnderlyingCursor(entry.getKey())) { 348 // If we're in a requery and we're still around, remove the requery key 349 // We're good here, the cached change (delete/update) is on its way to UP 350 values.remove(REQUERY_COLUMN); 351 LogUtils.i(TAG, new Error(), 352 "IN resetCursor, remove requery column from %s", entry.getKey()); 353 } else { 354 // Keep the deleted count up-to-date; remove the cache entry 355 if (values.containsKey(DELETED_COLUMN)) { 356 mDeletedCount--; 357 LogUtils.i(TAG, new Error(), 358 "IN resetCursor, sDeletedCount decremented to: %d by %s", 359 mDeletedCount, entry.getKey()); 360 } 361 // Remove the entry 362 iter.remove(); 363 } 364 } 365 366 // Swap cursor 367 if (mUnderlyingCursor != null) { 368 close(); 369 } 370 mUnderlyingCursor = newCursor; 371 372 mPosition = -1; 373 mUnderlyingCursor.moveToPosition(mPosition); 374 if (!mCursorObserverRegistered) { 375 mUnderlyingCursor.registerContentObserver(mCursorObserver); 376 mCursorObserverRegistered = true; 377 } 378 mRefreshRequired = false; 379 } 380 } 381 382 /** 383 * Add a listener for this cursor; we'll notify it when our data changes 384 */ 385 public void addListener(ConversationListener listener) { 386 synchronized (mListeners) { 387 if (!mListeners.contains(listener)) { 388 mListeners.add(listener); 389 } else { 390 LogUtils.i(TAG, "Ignoring duplicate add of listener"); 391 } 392 } 393 } 394 395 /** 396 * Remove a listener for this cursor 397 */ 398 public void removeListener(ConversationListener listener) { 399 synchronized(mListeners) { 400 mListeners.remove(listener); 401 } 402 } 403 404 /** 405 * Generate a forwarding Uri to ConversationProvider from an original Uri. We do this by 406 * changing the authority to ours, but otherwise leaving the Uri intact. 407 * NOTE: This won't handle query parameters, so the functionality will need to be added if 408 * parameters are used in the future 409 * @param uri the uri 410 * @return a forwarding uri to ConversationProvider 411 */ 412 private static String uriToCachingUriString (Uri uri) { 413 String provider = uri.getAuthority(); 414 return uri.getScheme() + "://" + ConversationProvider.AUTHORITY 415 + "/" + provider + uri.getPath(); 416 } 417 418 /** 419 * Regenerate the original Uri from a forwarding (ConversationProvider) Uri 420 * NOTE: See note above for uriToCachingUri 421 * @param uri the forwarding Uri 422 * @return the original Uri 423 */ 424 private static Uri uriFromCachingUri(Uri uri) { 425 String authority = uri.getAuthority(); 426 // Don't modify uri's that aren't ours 427 if (!authority.equals(ConversationProvider.AUTHORITY)) { 428 return uri; 429 } 430 List<String> path = uri.getPathSegments(); 431 Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0)); 432 for (int i = 1; i < path.size(); i++) { 433 builder.appendPath(path.get(i)); 434 } 435 return builder.build(); 436 } 437 438 private static String uriStringFromCachingUri(Uri uri) { 439 Uri underlyingUri = uriFromCachingUri(uri); 440 // Remember to decode the underlying Uri as it might be encoded (as w/ Gmail) 441 return Uri.decode(underlyingUri.toString()); 442 } 443 444 public void setConversationColumn(String uriString, String columnName, Object value) { 445 synchronized (mCacheMapLock) { 446 cacheValue(uriString, columnName, value); 447 } 448 notifyDataChanged(); 449 } 450 451 /** 452 * Cache a column name/value pair for a given Uri 453 * @param uriString the Uri for which the column name/value pair applies 454 * @param columnName the column name 455 * @param value the value to be cached 456 */ 457 private void cacheValue(String uriString, String columnName, Object value) { 458 // Calling this method off the UI thread will mess with ListView's reading of the cursor's 459 // count 460 if (offUiThread()) { 461 LogUtils.e(TAG, new Error(), "cacheValue incorrectly being called from non-UI thread"); 462 } 463 464 synchronized (mCacheMapLock) { 465 // Get the map for our uri 466 ContentValues map = mCacheMap.get(uriString); 467 // Create one if necessary 468 if (map == null) { 469 map = new ContentValues(); 470 mCacheMap.put(uriString, map); 471 } 472 // If we're caching a deletion, add to our count 473 if (columnName == DELETED_COLUMN) { 474 final boolean state = (Boolean)value; 475 final boolean hasValue = map.get(columnName) != null; 476 if (state && !hasValue) { 477 mDeletedCount++; 478 if (DEBUG) { 479 LogUtils.i(TAG, "Deleted %s, incremented deleted count=%d", uriString, 480 mDeletedCount); 481 } 482 } else if (!state && hasValue) { 483 mDeletedCount--; 484 map.remove(columnName); 485 if (DEBUG) { 486 LogUtils.i(TAG, "Undeleted %s, decremented deleted count=%d", uriString, 487 mDeletedCount); 488 } 489 return; 490 } else if (!state) { 491 // Trying to undelete, but it's not deleted; just return 492 if (DEBUG) { 493 LogUtils.i(TAG, "Undeleted %s, IGNORING, deleted count=%d", uriString, 494 mDeletedCount); 495 } 496 return; 497 } 498 } 499 // ContentValues has no generic "put", so we must test. For now, the only classes 500 // of values implemented are Boolean/Integer/String, though others are trivially 501 // added 502 if (value instanceof Boolean) { 503 map.put(columnName, ((Boolean) value).booleanValue() ? 1 : 0); 504 } else if (value instanceof Integer) { 505 map.put(columnName, (Integer) value); 506 } else if (value instanceof String) { 507 map.put(columnName, (String) value); 508 } else { 509 final String cname = value.getClass().getName(); 510 throw new IllegalArgumentException("Value class not compatible with cache: " 511 + cname); 512 } 513 if (mRefreshTask != null) { 514 map.put(REQUERY_COLUMN, 1); 515 } 516 if (DEBUG && (columnName != DELETED_COLUMN)) { 517 LogUtils.i(TAG, "Caching value for %s: %s", uriString, columnName); 518 } 519 } 520 } 521 522 /** 523 * Get the cached value for the provided column; we special case -1 as the "deleted" column 524 * @param columnIndex the index of the column whose cached value we want to retrieve 525 * @return the cached value for this column, or null if there is none 526 */ 527 private Object getCachedValue(int columnIndex) { 528 String uri = mUnderlyingCursor.getString(sUriColumnIndex); 529 return getCachedValue(uri, columnIndex); 530 } 531 532 private Object getCachedValue(String uri, int columnIndex) { 533 ContentValues uriMap = mCacheMap.get(uri); 534 if (uriMap != null) { 535 String columnName; 536 if (columnIndex == DELETED_COLUMN_INDEX) { 537 columnName = DELETED_COLUMN; 538 } else { 539 columnName = mColumnNames[columnIndex]; 540 } 541 return uriMap.get(columnName); 542 } 543 return null; 544 } 545 546 /** 547 * When the underlying cursor changes, we want to alert the listener 548 */ 549 private void underlyingChanged() { 550 synchronized(mCacheMapLock) { 551 if (mCursorObserverRegistered) { 552 try { 553 mUnderlyingCursor.unregisterContentObserver(mCursorObserver); 554 } catch (IllegalStateException e) { 555 // Maybe the cursor was GC'd? 556 } 557 mCursorObserverRegistered = false; 558 } 559 mRefreshRequired = true; 560 if (!mPaused) { 561 notifyRefreshRequired(); 562 } 563 } 564 } 565 566 /** 567 * Must be called on UI thread; notify listeners that a refresh is required 568 */ 569 private void notifyRefreshRequired() { 570 if (DEBUG) { 571 LogUtils.i(TAG, "[Notify " + mName + ": onRefreshRequired()]"); 572 } 573 if (!mDeferSync) { 574 synchronized(mListeners) { 575 for (ConversationListener listener: mListeners) { 576 listener.onRefreshRequired(); 577 } 578 } 579 } 580 } 581 582 /** 583 * Must be called on UI thread; notify listeners that a new cursor is ready 584 */ 585 private void notifyRefreshReady() { 586 if (DEBUG) { 587 LogUtils.i(TAG, "[Notify " + mName + ": onRefreshReady(), " + mListeners.size() + 588 " listeners]"); 589 } 590 synchronized(mListeners) { 591 for (ConversationListener listener: mListeners) { 592 listener.onRefreshReady(); 593 } 594 } 595 } 596 597 /** 598 * Must be called on UI thread; notify listeners that data has changed 599 */ 600 private void notifyDataChanged() { 601 if (DEBUG) { 602 LogUtils.i(TAG, "[Notify " + mName + ": onDataSetChanged()]"); 603 } 604 synchronized(mListeners) { 605 for (ConversationListener listener: mListeners) { 606 listener.onDataSetChanged(); 607 } 608 } 609 } 610 611 /** 612 * Put the refreshed cursor in place (called by the UI) 613 */ 614 public void sync() { 615 if (mRequeryCursor == null) { 616 // This can happen during an animated deletion, if the UI isn't keeping track, or 617 // if a new query intervened (i.e. user changed folders) 618 if (DEBUG) { 619 LogUtils.i(TAG, "[sync() " + mName + "; no requery cursor]"); 620 } 621 return; 622 } 623 synchronized(mCacheMapLock) { 624 if (DEBUG) { 625 LogUtils.i(TAG, "[sync() " + mName+ "]"); 626 } 627 resetCursor(mRequeryCursor); 628 mRequeryCursor = null; 629 mRefreshTask = null; 630 mRefreshReady = false; 631 } 632 notifyDataChanged(); 633 } 634 635 public boolean isRefreshRequired() { 636 return mRefreshRequired; 637 } 638 639 public boolean isRefreshReady() { 640 return mRefreshReady; 641 } 642 643 /** 644 * Cancel a refresh in progress 645 */ 646 public void cancelRefresh() { 647 if (DEBUG) { 648 LogUtils.i(TAG, "[cancelRefresh() " + mName + "]"); 649 } 650 synchronized(mCacheMapLock) { 651 if (mRefreshTask != null) { 652 mRefreshTask.cancel(true); 653 mRefreshTask = null; 654 } 655 mRefreshReady = false; 656 // If we have the cursor, close it; otherwise, it will get closed when the query 657 // finishes (it checks sRefreshInProgress) 658 if (mRequeryCursor != null) { 659 mRequeryCursor.close(); 660 mRequeryCursor = null; 661 } 662 } 663 } 664 665 /** 666 * Get a list of deletions from ConversationCursor to the refreshed cursor that hasn't yet 667 * been swapped into place; this allows the UI to animate these away if desired 668 * @return a list of positions deleted in ConversationCursor 669 */ 670 public ArrayList<Integer> getRefreshDeletions () { 671 return EMPTY_DELETION_LIST; 672 } 673 674 /** 675 * When we get a requery from the UI, we'll do it, but also clear the cache. The listener is 676 * notified when the requery is complete 677 * NOTE: This will have to change, of course, when we start using loaders... 678 */ 679 public boolean refresh() { 680 if (DEBUG) { 681 LogUtils.i(TAG, "[refresh() " + mName + "]"); 682 } 683 synchronized(mCacheMapLock) { 684 if (mRefreshTask != null) { 685 if (DEBUG) { 686 LogUtils.i(TAG, "[refresh() " + mName + " returning; already running %d]", 687 mRefreshTask.hashCode()); 688 } 689 return false; 690 } 691 mRefreshTask = new RefreshTask(); 692 mRefreshTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 693 } 694 return true; 695 } 696 697 public void disable() { 698 close(); 699 mCacheMap.clear(); 700 mListeners.clear(); 701 mUnderlyingCursor = null; 702 } 703 704 @Override 705 public void close() { 706 if (mUnderlyingCursor != null && !mUnderlyingCursor.isClosed()) { 707 // Unregister our observer on the underlying cursor and close as usual 708 if (mCursorObserverRegistered) { 709 try { 710 mUnderlyingCursor.unregisterContentObserver(mCursorObserver); 711 } catch (IllegalStateException e) { 712 // Maybe the cursor got GC'd? 713 } 714 mCursorObserverRegistered = false; 715 } 716 mUnderlyingCursor.close(); 717 } 718 } 719 720 /** 721 * Move to the next not-deleted item in the conversation 722 */ 723 @Override 724 public boolean moveToNext() { 725 while (true) { 726 boolean ret = mUnderlyingCursor.moveToNext(); 727 if (!ret) return false; 728 if (getCachedValue(DELETED_COLUMN_INDEX) instanceof Integer) continue; 729 mPosition++; 730 return true; 731 } 732 } 733 734 /** 735 * Move to the previous not-deleted item in the conversation 736 */ 737 @Override 738 public boolean moveToPrevious() { 739 while (true) { 740 boolean ret = mUnderlyingCursor.moveToPrevious(); 741 if (!ret) return false; 742 if (getCachedValue(DELETED_COLUMN_INDEX) instanceof Integer) continue; 743 mPosition--; 744 return true; 745 } 746 } 747 748 @Override 749 public int getPosition() { 750 return mPosition; 751 } 752 753 /** 754 * The actual cursor's count must be decremented by the number we've deleted from the UI 755 */ 756 @Override 757 public int getCount() { 758 if (mUnderlyingCursor == null) { 759 throw new IllegalStateException( 760 "getCount() on disabled cursor: " + mName + "(" + qUri + ")"); 761 } 762 return mUnderlyingCursor.getCount() - mDeletedCount; 763 } 764 765 @Override 766 public boolean moveToFirst() { 767 if (mUnderlyingCursor == null) { 768 throw new IllegalStateException( 769 "moveToFirst() on disabled cursor: " + mName + "(" + qUri + ")"); 770 } 771 mUnderlyingCursor.moveToPosition(-1); 772 mPosition = -1; 773 return moveToNext(); 774 } 775 776 @Override 777 public boolean moveToPosition(int pos) { 778 if (mUnderlyingCursor == null) { 779 throw new IllegalStateException( 780 "moveToPosition() on disabled cursor: " + mName + "(" + qUri + ")"); 781 } 782 if (pos == mPosition) return true; 783 if (pos > mPosition) { 784 while (pos > mPosition) { 785 if (!moveToNext()) { 786 return false; 787 } 788 } 789 return true; 790 } else if (pos == 0) { 791 return moveToFirst(); 792 } else { 793 while (pos < mPosition) { 794 if (!moveToPrevious()) { 795 return false; 796 } 797 } 798 return true; 799 } 800 } 801 802 /** 803 * Make sure mPosition is correct after locally deleting/undeleting items 804 */ 805 private void recalibratePosition() { 806 int pos = mPosition; 807 moveToFirst(); 808 moveToPosition(pos); 809 } 810 811 @Override 812 public boolean moveToLast() { 813 throw new UnsupportedOperationException("moveToLast unsupported!"); 814 } 815 816 @Override 817 public boolean move(int offset) { 818 throw new UnsupportedOperationException("move unsupported!"); 819 } 820 821 /** 822 * We need to override all of the getters to make sure they look at cached values before using 823 * the values in the underlying cursor 824 */ 825 @Override 826 public double getDouble(int columnIndex) { 827 Object obj = getCachedValue(columnIndex); 828 if (obj != null) return (Double)obj; 829 return mUnderlyingCursor.getDouble(columnIndex); 830 } 831 832 @Override 833 public float getFloat(int columnIndex) { 834 Object obj = getCachedValue(columnIndex); 835 if (obj != null) return (Float)obj; 836 return mUnderlyingCursor.getFloat(columnIndex); 837 } 838 839 @Override 840 public int getInt(int columnIndex) { 841 Object obj = getCachedValue(columnIndex); 842 if (obj != null) return (Integer)obj; 843 return mUnderlyingCursor.getInt(columnIndex); 844 } 845 846 @Override 847 public long getLong(int columnIndex) { 848 Object obj = getCachedValue(columnIndex); 849 if (obj != null) return (Long)obj; 850 return mUnderlyingCursor.getLong(columnIndex); 851 } 852 853 @Override 854 public short getShort(int columnIndex) { 855 Object obj = getCachedValue(columnIndex); 856 if (obj != null) return (Short)obj; 857 return mUnderlyingCursor.getShort(columnIndex); 858 } 859 860 @Override 861 public String getString(int columnIndex) { 862 // If we're asking for the Uri for the conversation list, we return a forwarding URI 863 // so that we can intercept update/delete and handle it ourselves 864 if (columnIndex == sUriColumnIndex) { 865 Uri uri = Uri.parse(mUnderlyingCursor.getString(columnIndex)); 866 return uriToCachingUriString(uri); 867 } 868 Object obj = getCachedValue(columnIndex); 869 if (obj != null) return (String)obj; 870 return mUnderlyingCursor.getString(columnIndex); 871 } 872 873 @Override 874 public byte[] getBlob(int columnIndex) { 875 Object obj = getCachedValue(columnIndex); 876 if (obj != null) return (byte[])obj; 877 return mUnderlyingCursor.getBlob(columnIndex); 878 } 879 880 /** 881 * Observer of changes to underlying data 882 */ 883 private class CursorObserver extends ContentObserver { 884 public CursorObserver() { 885 super(null); 886 } 887 888 @Override 889 public void onChange(boolean selfChange) { 890 // If we're here, then something outside of the UI has changed the data, and we 891 // must query the underlying provider for that data 892 ConversationCursor.this.underlyingChanged(); 893 } 894 } 895 896 /** 897 * ConversationProvider is the ContentProvider for our forwarding Uri's; it passes queries 898 * and inserts directly, and caches updates/deletes before passing them through. The caching 899 * will cause a redraw of the list with updated values. 900 */ 901 public abstract static class ConversationProvider extends ContentProvider { 902 public static String AUTHORITY; 903 904 /** 905 * Allows the implementing provider to specify the authority that should be used. 906 */ 907 protected abstract String getAuthority(); 908 909 @Override 910 public boolean onCreate() { 911 sProvider = this; 912 AUTHORITY = getAuthority(); 913 return true; 914 } 915 916 @Override 917 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 918 String sortOrder) { 919 return sResolver.query( 920 uriFromCachingUri(uri), projection, selection, selectionArgs, sortOrder); 921 } 922 923 @Override 924 public Uri insert(Uri uri, ContentValues values) { 925 insertLocal(uri, values); 926 return ProviderExecute.opInsert(uri, values); 927 } 928 929 @Override 930 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { 931 throw new IllegalStateException("Unexpected call to ConversationProvider.delete"); 932// updateLocal(uri, values); 933 // return ProviderExecute.opUpdate(uri, values); 934 } 935 936 @Override 937 public int delete(Uri uri, String selection, String[] selectionArgs) { 938 throw new IllegalStateException("Unexpected call to ConversationProvider.delete"); 939 //deleteLocal(uri); 940 // return ProviderExecute.opDelete(uri); 941 } 942 943 @Override 944 public String getType(Uri uri) { 945 return null; 946 } 947 948 /** 949 * Quick and dirty class that executes underlying provider CRUD operations on a background 950 * thread. 951 */ 952 static class ProviderExecute implements Runnable { 953 static final int DELETE = 0; 954 static final int INSERT = 1; 955 static final int UPDATE = 2; 956 957 final int mCode; 958 final Uri mUri; 959 final ContentValues mValues; //HEHEH 960 961 ProviderExecute(int code, Uri uri, ContentValues values) { 962 mCode = code; 963 mUri = uriFromCachingUri(uri); 964 mValues = values; 965 } 966 967 ProviderExecute(int code, Uri uri) { 968 this(code, uri, null); 969 } 970 971 static Uri opInsert(Uri uri, ContentValues values) { 972 ProviderExecute e = new ProviderExecute(INSERT, uri, values); 973 if (offUiThread()) return (Uri)e.go(); 974 new Thread(e).start(); 975 return null; 976 } 977 978 static int opDelete(Uri uri) { 979 ProviderExecute e = new ProviderExecute(DELETE, uri); 980 if (offUiThread()) return (Integer)e.go(); 981 new Thread(new ProviderExecute(DELETE, uri)).start(); 982 return 0; 983 } 984 985 static int opUpdate(Uri uri, ContentValues values) { 986 ProviderExecute e = new ProviderExecute(UPDATE, uri, values); 987 if (offUiThread()) return (Integer)e.go(); 988 new Thread(e).start(); 989 return 0; 990 } 991 992 @Override 993 public void run() { 994 go(); 995 } 996 997 public Object go() { 998 switch(mCode) { 999 case DELETE: 1000 return sResolver.delete(mUri, null, null); 1001 case INSERT: 1002 return sResolver.insert(mUri, mValues); 1003 case UPDATE: 1004 return sResolver.update(mUri, mValues, null, null); 1005 default: 1006 return null; 1007 } 1008 } 1009 } 1010 1011 private void insertLocal(Uri uri, ContentValues values) { 1012 // Placeholder for now; there's no local insert 1013 } 1014 1015 private int mUndoSequence = 0; 1016 private ArrayList<Uri> mUndoDeleteUris = new ArrayList<Uri>(); 1017 1018 void addToUndoSequence(Uri uri) { 1019 if (sSequence != mUndoSequence) { 1020 mUndoSequence = sSequence; 1021 mUndoDeleteUris.clear(); 1022 } 1023 mUndoDeleteUris.add(uri); 1024 } 1025 1026 @VisibleForTesting 1027 void deleteLocal(Uri uri, ConversationCursor conversationCursor) { 1028 String uriString = uriStringFromCachingUri(uri); 1029 conversationCursor.cacheValue(uriString, DELETED_COLUMN, true); 1030 addToUndoSequence(uri); 1031 } 1032 1033 @VisibleForTesting 1034 void undeleteLocal(Uri uri, ConversationCursor conversationCursor) { 1035 String uriString = uriStringFromCachingUri(uri); 1036 conversationCursor.cacheValue(uriString, DELETED_COLUMN, false); 1037 } 1038 1039 void setMostlyDead(Conversation conv, ConversationCursor conversationCursor) { 1040 Uri uri = conv.uri; 1041 String uriString = uriStringFromCachingUri(uri); 1042 conversationCursor.setMostlyDead(uriString, conv); 1043 LogUtils.i(TAG, "[Mostly dead, deferring: %s", uri); 1044 addToUndoSequence(uri); 1045 } 1046 1047 void commitMostlyDead(Conversation conv, ConversationCursor conversationCursor) { 1048 conversationCursor.commitMostlyDead(conv); 1049 } 1050 1051 boolean clearMostlyDead(Uri uri, ConversationCursor conversationCursor) { 1052 String uriString = uriStringFromCachingUri(uri); 1053 return conversationCursor.clearMostlyDead(uriString); 1054 } 1055 1056 public void undo(ConversationCursor conversationCursor) { 1057 if (sSequence == mUndoSequence) { 1058 for (Uri uri: mUndoDeleteUris) { 1059 if (!clearMostlyDead(uri, conversationCursor)) { 1060 undeleteLocal(uri, conversationCursor); 1061 } 1062 } 1063 mUndoSequence = 0; 1064 conversationCursor.recalibratePosition(); 1065 } 1066 } 1067 1068 @VisibleForTesting 1069 void updateLocal(Uri uri, ContentValues values, ConversationCursor conversationCursor) { 1070 if (values == null) { 1071 return; 1072 } 1073 String uriString = uriStringFromCachingUri(uri); 1074 for (String columnName: values.keySet()) { 1075 conversationCursor.cacheValue(uriString, columnName, values.get(columnName)); 1076 } 1077 } 1078 1079 public int apply(ArrayList<ConversationOperation> ops, 1080 ConversationCursor conversationCursor) { 1081 final HashMap<String, ArrayList<ContentProviderOperation>> batchMap = 1082 new HashMap<String, ArrayList<ContentProviderOperation>>(); 1083 // Increment sequence count 1084 sSequence++; 1085 1086 // Execute locally and build CPO's for underlying provider 1087 boolean recalibrateRequired = false; 1088 for (ConversationOperation op: ops) { 1089 Uri underlyingUri = uriFromCachingUri(op.mUri); 1090 String authority = underlyingUri.getAuthority(); 1091 ArrayList<ContentProviderOperation> authOps = batchMap.get(authority); 1092 if (authOps == null) { 1093 authOps = new ArrayList<ContentProviderOperation>(); 1094 batchMap.put(authority, authOps); 1095 } 1096 ContentProviderOperation cpo = op.execute(underlyingUri); 1097 if (cpo != null) { 1098 authOps.add(cpo); 1099 } 1100 // Keep track of whether our operations require recalibrating the cursor position 1101 if (op.mRecalibrateRequired) { 1102 recalibrateRequired = true; 1103 } 1104 } 1105 1106 // Recalibrate cursor position if required 1107 if (recalibrateRequired) { 1108 conversationCursor.recalibratePosition(); 1109 } 1110 // Notify listeners that data has changed 1111 conversationCursor.notifyDataChanged(); 1112 1113 // Send changes to underlying provider 1114 for (String authority: batchMap.keySet()) { 1115 try { 1116 if (offUiThread()) { 1117 sResolver.applyBatch(authority, batchMap.get(authority)); 1118 } else { 1119 final String auth = authority; 1120 new Thread(new Runnable() { 1121 @Override 1122 public void run() { 1123 try { 1124 sResolver.applyBatch(auth, batchMap.get(auth)); 1125 } catch (RemoteException e) { 1126 } catch (OperationApplicationException e) { 1127 } 1128 } 1129 }).start(); 1130 } 1131 } catch (RemoteException e) { 1132 } catch (OperationApplicationException e) { 1133 } 1134 } 1135 return sSequence; 1136 } 1137 } 1138 1139 void setMostlyDead(String uriString, Conversation conv) { 1140 cacheValue(uriString, 1141 UIProvider.ConversationColumns.FLAGS, Conversation.FLAG_MOSTLY_DEAD); 1142 conv.convFlags |= Conversation.FLAG_MOSTLY_DEAD; 1143 sMostlyDead.add(conv); 1144 mDeferSync = true; 1145 } 1146 1147 void commitMostlyDead(Conversation conv) { 1148 conv.convFlags &= ~Conversation.FLAG_MOSTLY_DEAD; 1149 sMostlyDead.remove(conv); 1150 LogUtils.i(TAG, "[All dead: %s]", conv.uri); 1151 if (sMostlyDead.isEmpty()) { 1152 mDeferSync = false; 1153 checkNotifyUI(); 1154 } 1155 } 1156 1157 boolean clearMostlyDead(String uriString) { 1158 Object val = getCachedValue(uriString, 1159 UIProvider.CONVERSATION_FLAGS_COLUMN); 1160 if (val != null) { 1161 int flags = ((Integer)val).intValue(); 1162 if ((flags & Conversation.FLAG_MOSTLY_DEAD) != 0) { 1163 cacheValue(uriString, UIProvider.ConversationColumns.FLAGS, 1164 flags &= ~Conversation.FLAG_MOSTLY_DEAD); 1165 return true; 1166 } 1167 } 1168 return false; 1169 } 1170 1171 1172 1173 1174 /** 1175 * ConversationOperation is the encapsulation of a ContentProvider operation to be performed 1176 * atomically as part of a "batch" operation. 1177 */ 1178 public class ConversationOperation { 1179 private static final int MOSTLY = 0x80; 1180 public static final int DELETE = 0; 1181 public static final int INSERT = 1; 1182 public static final int UPDATE = 2; 1183 public static final int ARCHIVE = 3; 1184 public static final int MUTE = 4; 1185 public static final int REPORT_SPAM = 5; 1186 public static final int MOSTLY_ARCHIVE = MOSTLY | ARCHIVE; 1187 public static final int MOSTLY_DELETE = MOSTLY | DELETE; 1188 1189 private final int mType; 1190 private final Uri mUri; 1191 private final Conversation mConversation; 1192 private final ContentValues mValues; 1193 // True if an updated item should be removed locally (from ConversationCursor) 1194 // This would be the case for a folder change in which the conversation is no longer 1195 // in the folder represented by the ConversationCursor 1196 private final boolean mLocalDeleteOnUpdate; 1197 // After execution, this indicates whether or not the operation requires recalibration of 1198 // the current cursor position (i.e. it removed or added items locally) 1199 private boolean mRecalibrateRequired = true; 1200 // Whether this item is already mostly dead 1201 private final boolean mMostlyDead; 1202 1203 /** 1204 * Set to true to immediately notify any {@link DataSetObserver}s watching the global 1205 * {@link ConversationCursor} upon applying the change to the data cache. You would not 1206 * want to do this if a change you make is being handled specially, like an animated delete. 1207 * 1208 * TODO: move this to the application Controller, or whoever has a canonical reference 1209 * to a {@link ConversationCursor} to notify on. 1210 */ 1211 private final boolean mAutoNotify; 1212 1213 public ConversationOperation(int type, Conversation conv) { 1214 this(type, conv, null, false /* autoNotify */); 1215 } 1216 1217 public ConversationOperation(int type, Conversation conv, ContentValues values, 1218 boolean autoNotify) { 1219 mType = type; 1220 mUri = conv.uri; 1221 mConversation = conv; 1222 mValues = values; 1223 mLocalDeleteOnUpdate = conv.localDeleteOnUpdate; 1224 mAutoNotify = autoNotify; 1225 mMostlyDead = conv.isMostlyDead(); 1226 } 1227 1228 private ContentProviderOperation execute(Uri underlyingUri) { 1229 Uri uri = underlyingUri.buildUpon() 1230 .appendQueryParameter(UIProvider.SEQUENCE_QUERY_PARAMETER, 1231 Integer.toString(sSequence)) 1232 .build(); 1233 ContentProviderOperation op = null; 1234 switch(mType) { 1235 case UPDATE: 1236 if (mLocalDeleteOnUpdate) { 1237 sProvider.deleteLocal(mUri, ConversationCursor.this); 1238 } else { 1239 sProvider.updateLocal(mUri, mValues, ConversationCursor.this); 1240 mRecalibrateRequired = false; 1241 } 1242 op = ContentProviderOperation.newUpdate(uri) 1243 .withValues(mValues) 1244 .build(); 1245 break; 1246 case INSERT: 1247 sProvider.insertLocal(mUri, mValues); 1248 op = ContentProviderOperation.newInsert(uri) 1249 .withValues(mValues).build(); 1250 break; 1251 // Destructive actions below! 1252 // "Mostly" operations are reflected globally, but not locally, except to set 1253 // FLAG_MOSTLY_DEAD in the conversation itself 1254 case DELETE: 1255 sProvider.deleteLocal(mUri, ConversationCursor.this); 1256 if (!mMostlyDead) { 1257 op = ContentProviderOperation.newDelete(uri).build(); 1258 } else { 1259 sProvider.commitMostlyDead(mConversation, ConversationCursor.this); 1260 } 1261 break; 1262 case MOSTLY_DELETE: 1263 sProvider.setMostlyDead(mConversation,ConversationCursor.this); 1264 op = ContentProviderOperation.newDelete(uri).build(); 1265 break; 1266 case ARCHIVE: 1267 sProvider.deleteLocal(mUri, ConversationCursor.this); 1268 if (!mMostlyDead) { 1269 // Create an update operation that represents archive 1270 op = ContentProviderOperation.newUpdate(uri).withValue( 1271 ConversationOperations.OPERATION_KEY, 1272 ConversationOperations.ARCHIVE) 1273 .build(); 1274 } else { 1275 sProvider.commitMostlyDead(mConversation, ConversationCursor.this); 1276 } 1277 break; 1278 case MOSTLY_ARCHIVE: 1279 sProvider.setMostlyDead(mConversation, ConversationCursor.this); 1280 // Create an update operation that represents archive 1281 op = ContentProviderOperation.newUpdate(uri).withValue( 1282 ConversationOperations.OPERATION_KEY, ConversationOperations.ARCHIVE) 1283 .build(); 1284 break; 1285 case MUTE: 1286 if (mLocalDeleteOnUpdate) { 1287 sProvider.deleteLocal(mUri, ConversationCursor.this); 1288 } 1289 1290 // Create an update operation that represents mute 1291 op = ContentProviderOperation.newUpdate(uri).withValue( 1292 ConversationOperations.OPERATION_KEY, ConversationOperations.MUTE) 1293 .build(); 1294 break; 1295 case REPORT_SPAM: 1296 sProvider.deleteLocal(mUri, ConversationCursor.this); 1297 1298 // Create an update operation that represents report spam 1299 op = ContentProviderOperation.newUpdate(uri).withValue( 1300 ConversationOperations.OPERATION_KEY, 1301 ConversationOperations.REPORT_SPAM).build(); 1302 break; 1303 default: 1304 throw new UnsupportedOperationException( 1305 "No such ConversationOperation type: " + mType); 1306 } 1307 1308 // FIXME: this is a hack to notify conversation list of changes from conversation view. 1309 // The proper way to do this is to have the Controller handle the 'mark read' action. 1310 // It has a reference to this ConversationCursor so it can notify without using global 1311 // magic. 1312 if (mAutoNotify) { 1313 notifyDataSetChanged(); 1314 } 1315 1316 return op; 1317 } 1318 } 1319 1320 /** 1321 * For now, a single listener can be associated with the cursor, and for now we'll just 1322 * notify on deletions 1323 */ 1324 public interface ConversationListener { 1325 /** 1326 * Data in the underlying provider has changed; a refresh is required to sync up 1327 */ 1328 public void onRefreshRequired(); 1329 /** 1330 * We've completed a requested refresh of the underlying cursor 1331 */ 1332 public void onRefreshReady(); 1333 /** 1334 * The data underlying the cursor has changed; the UI should redraw the list 1335 */ 1336 public void onDataSetChanged(); 1337 } 1338 1339 @Override 1340 public boolean isFirst() { 1341 throw new UnsupportedOperationException(); 1342 } 1343 1344 @Override 1345 public boolean isLast() { 1346 throw new UnsupportedOperationException(); 1347 } 1348 1349 @Override 1350 public boolean isBeforeFirst() { 1351 throw new UnsupportedOperationException(); 1352 } 1353 1354 @Override 1355 public boolean isAfterLast() { 1356 throw new UnsupportedOperationException(); 1357 } 1358 1359 @Override 1360 public int getColumnIndex(String columnName) { 1361 return mUnderlyingCursor.getColumnIndex(columnName); 1362 } 1363 1364 @Override 1365 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { 1366 return mUnderlyingCursor.getColumnIndexOrThrow(columnName); 1367 } 1368 1369 @Override 1370 public String getColumnName(int columnIndex) { 1371 return mUnderlyingCursor.getColumnName(columnIndex); 1372 } 1373 1374 @Override 1375 public String[] getColumnNames() { 1376 return mUnderlyingCursor.getColumnNames(); 1377 } 1378 1379 @Override 1380 public int getColumnCount() { 1381 return mUnderlyingCursor.getColumnCount(); 1382 } 1383 1384 @Override 1385 public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) { 1386 throw new UnsupportedOperationException(); 1387 } 1388 1389 @Override 1390 public int getType(int columnIndex) { 1391 return mUnderlyingCursor.getType(columnIndex); 1392 } 1393 1394 @Override 1395 public boolean isNull(int columnIndex) { 1396 throw new UnsupportedOperationException(); 1397 } 1398 1399 @Override 1400 public void deactivate() { 1401 throw new UnsupportedOperationException(); 1402 } 1403 1404 @Override 1405 public boolean isClosed() { 1406 return mUnderlyingCursor == null || mUnderlyingCursor.isClosed(); 1407 } 1408 1409 @Override 1410 public void registerContentObserver(ContentObserver observer) { 1411 // Nope. We never notify of underlying changes on this channel, since the cursor watches 1412 // internally and offers onRefreshRequired/onRefreshReady to accomplish the same thing. 1413 } 1414 1415 @Override 1416 public void unregisterContentObserver(ContentObserver observer) { 1417 // See above. 1418 } 1419 1420 @Override 1421 public void registerDataSetObserver(DataSetObserver observer) { 1422 mDataSetObservable.registerObserver(observer); 1423 } 1424 1425 @Override 1426 public void unregisterDataSetObserver(DataSetObserver observer) { 1427 mDataSetObservable.unregisterObserver(observer); 1428 } 1429 1430 public void notifyDataSetChanged() { 1431 mDataSetObservable.notifyChanged(); 1432 } 1433 1434 @Override 1435 public void setNotificationUri(ContentResolver cr, Uri uri) { 1436 throw new UnsupportedOperationException(); 1437 } 1438 1439 @Override 1440 public boolean getWantsAllOnMoveCalls() { 1441 throw new UnsupportedOperationException(); 1442 } 1443 1444 @Override 1445 public Bundle getExtras() { 1446 throw new UnsupportedOperationException(); 1447 } 1448 1449 @Override 1450 public Bundle respond(Bundle extras) { 1451 return mUnderlyingCursor.respond(extras); 1452 } 1453 1454 @Override 1455 public boolean requery() { 1456 return true; 1457 } 1458 1459 // Below are methods that update Conversation data (update/delete) 1460 1461 public int updateBoolean(Context context, Conversation conversation, String columnName, 1462 boolean value) { 1463 return updateBoolean(context, Arrays.asList(conversation), columnName, value); 1464 } 1465 1466 /** 1467 * Update an integer column for a group of conversations (see updateValues below) 1468 */ 1469 public int updateInt(Context context, Collection<Conversation> conversations, 1470 String columnName, int value) { 1471 ContentValues cv = new ContentValues(); 1472 cv.put(columnName, value); 1473 return updateValues(context, conversations, cv); 1474 } 1475 1476 /** 1477 * Update a string column for a group of conversations (see updateValues below) 1478 */ 1479 public int updateBoolean(Context context, Collection<Conversation> conversations, 1480 String columnName, boolean value) { 1481 ContentValues cv = new ContentValues(); 1482 cv.put(columnName, value); 1483 return updateValues(context, conversations, cv); 1484 } 1485 1486 /** 1487 * Update a string column for a group of conversations (see updateValues below) 1488 */ 1489 public int updateString(Context context, Collection<Conversation> conversations, 1490 String columnName, String value) { 1491 ContentValues cv = new ContentValues(); 1492 cv.put(columnName, value); 1493 return updateValues(context, conversations, cv); 1494 } 1495 1496 public int updateBoolean(Context context, String conversationUri, String columnName, 1497 boolean value) { 1498 Conversation conv = new Conversation(); 1499 conv.uri = Uri.parse(conversationUri); 1500 return updateBoolean(context, conv, columnName, value); 1501 } 1502 1503 /** 1504 * Update a boolean column for a group of conversations, immediately in the UI and in a single 1505 * transaction in the underlying provider 1506 * @param conversations a collection of conversations 1507 * @param context the caller's context 1508 * @param columnName the column to update 1509 * @param value the new value 1510 * @return the sequence number of the operation (for undo) 1511 */ 1512 private int updateValues(Context context, Collection<Conversation> conversations, 1513 ContentValues values) { 1514 return apply(context, 1515 getOperationsForConversations(conversations, ConversationOperation.UPDATE, values)); 1516 } 1517 1518 private ArrayList<ConversationOperation> getOperationsForConversations( 1519 Collection<Conversation> conversations, int op, ContentValues values) { 1520 return getOperationsForConversations(conversations, op, values, false /* autoNotify */); 1521 } 1522 1523 private ArrayList<ConversationOperation> getOperationsForConversations( 1524 Collection<Conversation> conversations, int type, ContentValues values, 1525 boolean autoNotify) { 1526 final ArrayList<ConversationOperation> ops = Lists.newArrayList(); 1527 for (Conversation conv: conversations) { 1528 ConversationOperation op = new ConversationOperation(type, conv, values, autoNotify); 1529 ops.add(op); 1530 } 1531 return ops; 1532 } 1533 1534 /** 1535 * Delete a single conversation 1536 * @param context the caller's context 1537 * @return the sequence number of the operation (for undo) 1538 */ 1539 public int delete(Context context, Conversation conversation) { 1540 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1541 conversations.add(conversation); 1542 return delete(context, conversations); 1543 } 1544 1545 /** 1546 * Delete a single conversation 1547 * @param context the caller's context 1548 * @return the sequence number of the operation (for undo) 1549 */ 1550 public int mostlyArchive(Context context, Conversation conversation) { 1551 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1552 conversations.add(conversation); 1553 return archive(context, conversations); 1554 } 1555 1556 /** 1557 * Delete a single conversation 1558 * @param context the caller's context 1559 * @return the sequence number of the operation (for undo) 1560 */ 1561 public int mostlyDelete(Context context, Conversation conversation) { 1562 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1563 conversations.add(conversation); 1564 return delete(context, conversations); 1565 } 1566 1567 /** 1568 * Mark a single conversation read/unread. 1569 * @param context the caller's context 1570 * @param read true for read, false for unread 1571 * @return the sequence number of the operation (for undo) 1572 */ 1573 public int markRead(Context context, boolean read, Conversation conversation) { 1574 ContentValues values = new ContentValues(); 1575 values.put(ConversationColumns.READ, read); 1576 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1577 conversations.add(conversation); 1578 return apply( 1579 context, 1580 getOperationsForConversations(conversations, ConversationOperation.UPDATE, 1581 values, true /* autoNotify */)); 1582 } 1583 1584 // Convenience methods 1585 private int apply(Context context, ArrayList<ConversationOperation> operations) { 1586 return sProvider.apply(operations, this); 1587 } 1588 1589 private void undoLocal() { 1590 sProvider.undo(this); 1591 } 1592 1593 public void undo(final Context context, final Uri undoUri) { 1594 new Thread(new Runnable() { 1595 @Override 1596 public void run() { 1597 Cursor c = context.getContentResolver().query(undoUri, UIProvider.UNDO_PROJECTION, 1598 null, null, null); 1599 if (c != null) { 1600 c.close(); 1601 } 1602 } 1603 }).start(); 1604 undoLocal(); 1605 } 1606 1607 /** 1608 * Delete a group of conversations immediately in the UI and in a single transaction in the 1609 * underlying provider. See applyAction for argument descriptions 1610 */ 1611 public int delete(Context context, Collection<Conversation> conversations) { 1612 return applyAction(context, conversations, ConversationOperation.DELETE); 1613 } 1614 1615 /** 1616 * As above, for archive 1617 */ 1618 public int archive(Context context, Collection<Conversation> conversations) { 1619 return applyAction(context, conversations, ConversationOperation.ARCHIVE); 1620 } 1621 1622 /** 1623 * As above, for mute 1624 */ 1625 public int mute(Context context, Collection<Conversation> conversations) { 1626 return applyAction(context, conversations, ConversationOperation.MUTE); 1627 } 1628 1629 /** 1630 * As above, for report spam 1631 */ 1632 public int reportSpam(Context context, Collection<Conversation> conversations) { 1633 return applyAction(context, conversations, ConversationOperation.REPORT_SPAM); 1634 } 1635 1636 /** 1637 * As above, for mostly archive 1638 */ 1639 public int mostlyArchive(Context context, Collection<Conversation> conversations) { 1640 return applyAction(context, conversations, ConversationOperation.MOSTLY_ARCHIVE); 1641 } 1642 1643 /** 1644 * As above, for mostly delete 1645 */ 1646 public int mostlyDelete(Context context, Collection<Conversation> conversations) { 1647 return applyAction(context, conversations, ConversationOperation.MOSTLY_DELETE); 1648 } 1649 1650 /** 1651 * Convenience method for performing an operation on a group of conversations 1652 * @param context the caller's context 1653 * @param conversations the conversations to be affected 1654 * @param opAction the action to take 1655 * @return the sequence number of the operation applied in CC 1656 */ 1657 private int applyAction(Context context, Collection<Conversation> conversations, 1658 int opAction) { 1659 ArrayList<ConversationOperation> ops = Lists.newArrayList(); 1660 for (Conversation conv: conversations) { 1661 ConversationOperation op = 1662 new ConversationOperation(opAction, conv); 1663 ops.add(op); 1664 } 1665 return apply(context, ops); 1666 } 1667 1668}