ConversationCursor.java revision 7f602f7a64f176894ccb7942a6642f22584c3894
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 Collection<Conversation> 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 Collection<Conversation> 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 addToUndoSequence(uri); 1044 } 1045 1046 void commitMostlyDead(Conversation conv, ConversationCursor conversationCursor) { 1047 conversationCursor.commitMostlyDead(conv); 1048 } 1049 1050 boolean clearMostlyDead(Uri uri, ConversationCursor conversationCursor) { 1051 String uriString = uriStringFromCachingUri(uri); 1052 return conversationCursor.clearMostlyDead(uriString); 1053 } 1054 1055 public void undo(ConversationCursor conversationCursor) { 1056 if (sSequence == mUndoSequence) { 1057 for (Uri uri: mUndoDeleteUris) { 1058 if (!clearMostlyDead(uri, conversationCursor)) { 1059 undeleteLocal(uri, conversationCursor); 1060 } 1061 } 1062 mUndoSequence = 0; 1063 conversationCursor.recalibratePosition(); 1064 } 1065 } 1066 1067 @VisibleForTesting 1068 void updateLocal(Uri uri, ContentValues values, ConversationCursor conversationCursor) { 1069 if (values == null) { 1070 return; 1071 } 1072 String uriString = uriStringFromCachingUri(uri); 1073 for (String columnName: values.keySet()) { 1074 conversationCursor.cacheValue(uriString, columnName, values.get(columnName)); 1075 } 1076 } 1077 1078 public int apply(ArrayList<ConversationOperation> ops, 1079 ConversationCursor conversationCursor) { 1080 final HashMap<String, ArrayList<ContentProviderOperation>> batchMap = 1081 new HashMap<String, ArrayList<ContentProviderOperation>>(); 1082 // Increment sequence count 1083 sSequence++; 1084 1085 // Execute locally and build CPO's for underlying provider 1086 boolean recalibrateRequired = false; 1087 for (ConversationOperation op: ops) { 1088 Uri underlyingUri = uriFromCachingUri(op.mUri); 1089 String authority = underlyingUri.getAuthority(); 1090 ArrayList<ContentProviderOperation> authOps = batchMap.get(authority); 1091 if (authOps == null) { 1092 authOps = new ArrayList<ContentProviderOperation>(); 1093 batchMap.put(authority, authOps); 1094 } 1095 ContentProviderOperation cpo = op.execute(underlyingUri); 1096 if (cpo != null) { 1097 authOps.add(cpo); 1098 } 1099 // Keep track of whether our operations require recalibrating the cursor position 1100 if (op.mRecalibrateRequired) { 1101 recalibrateRequired = true; 1102 } 1103 } 1104 1105 // Notify listeners that data has changed 1106 conversationCursor.notifyDataChanged(); 1107 1108 // Recalibrate cursor position if required 1109 if (recalibrateRequired) { 1110 conversationCursor.recalibratePosition(); 1111 } 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 LogUtils.i(TAG, "[Mostly dead, deferring: %s] ", uriString); 1141 cacheValue(uriString, 1142 UIProvider.ConversationColumns.FLAGS, Conversation.FLAG_MOSTLY_DEAD); 1143 conv.convFlags |= Conversation.FLAG_MOSTLY_DEAD; 1144 sMostlyDead.add(conv); 1145 mDeferSync = true; 1146 } 1147 1148 void commitMostlyDead(Conversation conv) { 1149 conv.convFlags &= ~Conversation.FLAG_MOSTLY_DEAD; 1150 sMostlyDead.remove(conv); 1151 LogUtils.i(TAG, "[All dead: %s]", conv.uri); 1152 if (sMostlyDead.isEmpty()) { 1153 mDeferSync = false; 1154 checkNotifyUI(); 1155 } 1156 } 1157 1158 boolean clearMostlyDead(String uriString) { 1159 Object val = getCachedValue(uriString, 1160 UIProvider.CONVERSATION_FLAGS_COLUMN); 1161 if (val != null) { 1162 int flags = ((Integer)val).intValue(); 1163 if ((flags & Conversation.FLAG_MOSTLY_DEAD) != 0) { 1164 cacheValue(uriString, UIProvider.ConversationColumns.FLAGS, 1165 flags &= ~Conversation.FLAG_MOSTLY_DEAD); 1166 return true; 1167 } 1168 } 1169 return false; 1170 } 1171 1172 1173 1174 1175 /** 1176 * ConversationOperation is the encapsulation of a ContentProvider operation to be performed 1177 * atomically as part of a "batch" operation. 1178 */ 1179 public class ConversationOperation { 1180 private static final int MOSTLY = 0x80; 1181 public static final int DELETE = 0; 1182 public static final int INSERT = 1; 1183 public static final int UPDATE = 2; 1184 public static final int ARCHIVE = 3; 1185 public static final int MUTE = 4; 1186 public static final int REPORT_SPAM = 5; 1187 public static final int MOSTLY_ARCHIVE = MOSTLY | ARCHIVE; 1188 public static final int MOSTLY_DELETE = MOSTLY | DELETE; 1189 1190 private final int mType; 1191 private final Uri mUri; 1192 private final Conversation mConversation; 1193 private final ContentValues mValues; 1194 // True if an updated item should be removed locally (from ConversationCursor) 1195 // This would be the case for a folder change in which the conversation is no longer 1196 // in the folder represented by the ConversationCursor 1197 private final boolean mLocalDeleteOnUpdate; 1198 // After execution, this indicates whether or not the operation requires recalibration of 1199 // the current cursor position (i.e. it removed or added items locally) 1200 private boolean mRecalibrateRequired = true; 1201 // Whether this item is already mostly dead 1202 private final boolean mMostlyDead; 1203 1204 /** 1205 * Set to true to immediately notify any {@link DataSetObserver}s watching the global 1206 * {@link ConversationCursor} upon applying the change to the data cache. You would not 1207 * want to do this if a change you make is being handled specially, like an animated delete. 1208 * 1209 * TODO: move this to the application Controller, or whoever has a canonical reference 1210 * to a {@link ConversationCursor} to notify on. 1211 */ 1212 private final boolean mAutoNotify; 1213 1214 public ConversationOperation(int type, Conversation conv) { 1215 this(type, conv, null, false /* autoNotify */); 1216 } 1217 1218 public ConversationOperation(int type, Conversation conv, ContentValues values, 1219 boolean autoNotify) { 1220 mType = type; 1221 mUri = conv.uri; 1222 mConversation = conv; 1223 mValues = values; 1224 mLocalDeleteOnUpdate = conv.localDeleteOnUpdate; 1225 mAutoNotify = autoNotify; 1226 mMostlyDead = conv.isMostlyDead(); 1227 } 1228 1229 private ContentProviderOperation execute(Uri underlyingUri) { 1230 Uri uri = underlyingUri.buildUpon() 1231 .appendQueryParameter(UIProvider.SEQUENCE_QUERY_PARAMETER, 1232 Integer.toString(sSequence)) 1233 .build(); 1234 ContentProviderOperation op = null; 1235 switch(mType) { 1236 case UPDATE: 1237 if (mLocalDeleteOnUpdate) { 1238 sProvider.deleteLocal(mUri, ConversationCursor.this); 1239 } else { 1240 sProvider.updateLocal(mUri, mValues, ConversationCursor.this); 1241 mRecalibrateRequired = false; 1242 } 1243 op = ContentProviderOperation.newUpdate(uri) 1244 .withValues(mValues) 1245 .build(); 1246 break; 1247 case INSERT: 1248 sProvider.insertLocal(mUri, mValues); 1249 op = ContentProviderOperation.newInsert(uri) 1250 .withValues(mValues).build(); 1251 break; 1252 // Destructive actions below! 1253 // "Mostly" operations are reflected globally, but not locally, except to set 1254 // FLAG_MOSTLY_DEAD in the conversation itself 1255 case DELETE: 1256 sProvider.deleteLocal(mUri, ConversationCursor.this); 1257 if (!mMostlyDead) { 1258 op = ContentProviderOperation.newDelete(uri).build(); 1259 } else { 1260 sProvider.commitMostlyDead(mConversation, ConversationCursor.this); 1261 } 1262 break; 1263 case MOSTLY_DELETE: 1264 sProvider.setMostlyDead(mConversation,ConversationCursor.this); 1265 op = ContentProviderOperation.newDelete(uri).build(); 1266 break; 1267 case ARCHIVE: 1268 sProvider.deleteLocal(mUri, ConversationCursor.this); 1269 if (!mMostlyDead) { 1270 // Create an update operation that represents archive 1271 op = ContentProviderOperation.newUpdate(uri).withValue( 1272 ConversationOperations.OPERATION_KEY, 1273 ConversationOperations.ARCHIVE) 1274 .build(); 1275 } else { 1276 sProvider.commitMostlyDead(mConversation, ConversationCursor.this); 1277 } 1278 break; 1279 case MOSTLY_ARCHIVE: 1280 sProvider.setMostlyDead(mConversation, ConversationCursor.this); 1281 // Create an update operation that represents archive 1282 op = ContentProviderOperation.newUpdate(uri).withValue( 1283 ConversationOperations.OPERATION_KEY, ConversationOperations.ARCHIVE) 1284 .build(); 1285 break; 1286 case MUTE: 1287 if (mLocalDeleteOnUpdate) { 1288 sProvider.deleteLocal(mUri, ConversationCursor.this); 1289 } 1290 1291 // Create an update operation that represents mute 1292 op = ContentProviderOperation.newUpdate(uri).withValue( 1293 ConversationOperations.OPERATION_KEY, ConversationOperations.MUTE) 1294 .build(); 1295 break; 1296 case REPORT_SPAM: 1297 sProvider.deleteLocal(mUri, ConversationCursor.this); 1298 1299 // Create an update operation that represents report spam 1300 op = ContentProviderOperation.newUpdate(uri).withValue( 1301 ConversationOperations.OPERATION_KEY, 1302 ConversationOperations.REPORT_SPAM).build(); 1303 break; 1304 default: 1305 throw new UnsupportedOperationException( 1306 "No such ConversationOperation type: " + mType); 1307 } 1308 1309 // FIXME: this is a hack to notify conversation list of changes from conversation view. 1310 // The proper way to do this is to have the Controller handle the 'mark read' action. 1311 // It has a reference to this ConversationCursor so it can notify without using global 1312 // magic. 1313 if (mAutoNotify) { 1314 notifyDataSetChanged(); 1315 } 1316 1317 return op; 1318 } 1319 } 1320 1321 /** 1322 * For now, a single listener can be associated with the cursor, and for now we'll just 1323 * notify on deletions 1324 */ 1325 public interface ConversationListener { 1326 /** 1327 * Data in the underlying provider has changed; a refresh is required to sync up 1328 */ 1329 public void onRefreshRequired(); 1330 /** 1331 * We've completed a requested refresh of the underlying cursor 1332 */ 1333 public void onRefreshReady(); 1334 /** 1335 * The data underlying the cursor has changed; the UI should redraw the list 1336 */ 1337 public void onDataSetChanged(); 1338 } 1339 1340 @Override 1341 public boolean isFirst() { 1342 throw new UnsupportedOperationException(); 1343 } 1344 1345 @Override 1346 public boolean isLast() { 1347 throw new UnsupportedOperationException(); 1348 } 1349 1350 @Override 1351 public boolean isBeforeFirst() { 1352 throw new UnsupportedOperationException(); 1353 } 1354 1355 @Override 1356 public boolean isAfterLast() { 1357 throw new UnsupportedOperationException(); 1358 } 1359 1360 @Override 1361 public int getColumnIndex(String columnName) { 1362 return mUnderlyingCursor.getColumnIndex(columnName); 1363 } 1364 1365 @Override 1366 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { 1367 return mUnderlyingCursor.getColumnIndexOrThrow(columnName); 1368 } 1369 1370 @Override 1371 public String getColumnName(int columnIndex) { 1372 return mUnderlyingCursor.getColumnName(columnIndex); 1373 } 1374 1375 @Override 1376 public String[] getColumnNames() { 1377 return mUnderlyingCursor.getColumnNames(); 1378 } 1379 1380 @Override 1381 public int getColumnCount() { 1382 return mUnderlyingCursor.getColumnCount(); 1383 } 1384 1385 @Override 1386 public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) { 1387 throw new UnsupportedOperationException(); 1388 } 1389 1390 @Override 1391 public int getType(int columnIndex) { 1392 return mUnderlyingCursor.getType(columnIndex); 1393 } 1394 1395 @Override 1396 public boolean isNull(int columnIndex) { 1397 throw new UnsupportedOperationException(); 1398 } 1399 1400 @Override 1401 public void deactivate() { 1402 throw new UnsupportedOperationException(); 1403 } 1404 1405 @Override 1406 public boolean isClosed() { 1407 return mUnderlyingCursor == null || mUnderlyingCursor.isClosed(); 1408 } 1409 1410 @Override 1411 public void registerContentObserver(ContentObserver observer) { 1412 // Nope. We never notify of underlying changes on this channel, since the cursor watches 1413 // internally and offers onRefreshRequired/onRefreshReady to accomplish the same thing. 1414 } 1415 1416 @Override 1417 public void unregisterContentObserver(ContentObserver observer) { 1418 // See above. 1419 } 1420 1421 @Override 1422 public void registerDataSetObserver(DataSetObserver observer) { 1423 mDataSetObservable.registerObserver(observer); 1424 } 1425 1426 @Override 1427 public void unregisterDataSetObserver(DataSetObserver observer) { 1428 mDataSetObservable.unregisterObserver(observer); 1429 } 1430 1431 public void notifyDataSetChanged() { 1432 mDataSetObservable.notifyChanged(); 1433 } 1434 1435 @Override 1436 public void setNotificationUri(ContentResolver cr, Uri uri) { 1437 throw new UnsupportedOperationException(); 1438 } 1439 1440 @Override 1441 public boolean getWantsAllOnMoveCalls() { 1442 throw new UnsupportedOperationException(); 1443 } 1444 1445 @Override 1446 public Bundle getExtras() { 1447 throw new UnsupportedOperationException(); 1448 } 1449 1450 @Override 1451 public Bundle respond(Bundle extras) { 1452 if (mUnderlyingCursor != null) { 1453 return mUnderlyingCursor.respond(extras); 1454 } 1455 return Bundle.EMPTY; 1456 } 1457 1458 @Override 1459 public boolean requery() { 1460 return true; 1461 } 1462 1463 // Below are methods that update Conversation data (update/delete) 1464 1465 public int updateBoolean(Context context, Conversation conversation, String columnName, 1466 boolean value) { 1467 return updateBoolean(context, Arrays.asList(conversation), columnName, value); 1468 } 1469 1470 /** 1471 * Update an integer column for a group of conversations (see updateValues below) 1472 */ 1473 public int updateInt(Context context, Collection<Conversation> conversations, 1474 String columnName, int value) { 1475 ContentValues cv = new ContentValues(); 1476 cv.put(columnName, value); 1477 return updateValues(context, conversations, cv); 1478 } 1479 1480 /** 1481 * Update a string column for a group of conversations (see updateValues below) 1482 */ 1483 public int updateBoolean(Context context, Collection<Conversation> conversations, 1484 String columnName, boolean value) { 1485 ContentValues cv = new ContentValues(); 1486 cv.put(columnName, value); 1487 return updateValues(context, conversations, cv); 1488 } 1489 1490 /** 1491 * Update a string column for a group of conversations (see updateValues below) 1492 */ 1493 public int updateString(Context context, Collection<Conversation> conversations, 1494 String columnName, String value) { 1495 ContentValues cv = new ContentValues(); 1496 cv.put(columnName, value); 1497 return updateValues(context, conversations, cv); 1498 } 1499 1500 public int updateBoolean(Context context, String conversationUri, String columnName, 1501 boolean value) { 1502 Conversation conv = new Conversation(); 1503 conv.uri = Uri.parse(conversationUri); 1504 return updateBoolean(context, conv, columnName, value); 1505 } 1506 1507 /** 1508 * Update a boolean column for a group of conversations, immediately in the UI and in a single 1509 * transaction in the underlying provider 1510 * @param conversations a collection of conversations 1511 * @param context the caller's context 1512 * @param columnName the column to update 1513 * @param value the new value 1514 * @return the sequence number of the operation (for undo) 1515 */ 1516 private int updateValues(Context context, Collection<Conversation> conversations, 1517 ContentValues values) { 1518 return apply(context, 1519 getOperationsForConversations(conversations, ConversationOperation.UPDATE, values)); 1520 } 1521 1522 private ArrayList<ConversationOperation> getOperationsForConversations( 1523 Collection<Conversation> conversations, int op, ContentValues values) { 1524 return getOperationsForConversations(conversations, op, values, false /* autoNotify */); 1525 } 1526 1527 private ArrayList<ConversationOperation> getOperationsForConversations( 1528 Collection<Conversation> conversations, int type, ContentValues values, 1529 boolean autoNotify) { 1530 final ArrayList<ConversationOperation> ops = Lists.newArrayList(); 1531 for (Conversation conv: conversations) { 1532 ConversationOperation op = new ConversationOperation(type, conv, values, autoNotify); 1533 ops.add(op); 1534 } 1535 return ops; 1536 } 1537 1538 /** 1539 * Delete a single conversation 1540 * @param context the caller's context 1541 * @return the sequence number of the operation (for undo) 1542 */ 1543 public int delete(Context context, Conversation conversation) { 1544 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1545 conversations.add(conversation); 1546 return delete(context, conversations); 1547 } 1548 1549 /** 1550 * Delete a single conversation 1551 * @param context the caller's context 1552 * @return the sequence number of the operation (for undo) 1553 */ 1554 public int mostlyArchive(Context context, Conversation conversation) { 1555 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1556 conversations.add(conversation); 1557 return archive(context, conversations); 1558 } 1559 1560 /** 1561 * Delete a single conversation 1562 * @param context the caller's context 1563 * @return the sequence number of the operation (for undo) 1564 */ 1565 public int mostlyDelete(Context context, Conversation conversation) { 1566 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1567 conversations.add(conversation); 1568 return delete(context, conversations); 1569 } 1570 1571 /** 1572 * Mark a single conversation read/unread. 1573 * @param context the caller's context 1574 * @param read true for read, false for unread 1575 * @return the sequence number of the operation (for undo) 1576 */ 1577 public int markRead(Context context, boolean read, Conversation conversation) { 1578 ContentValues values = new ContentValues(); 1579 values.put(ConversationColumns.READ, read); 1580 ArrayList<Conversation> conversations = new ArrayList<Conversation>(); 1581 conversations.add(conversation); 1582 return apply( 1583 context, 1584 getOperationsForConversations(conversations, ConversationOperation.UPDATE, 1585 values, true /* autoNotify */)); 1586 } 1587 1588 // Convenience methods 1589 private int apply(Context context, ArrayList<ConversationOperation> operations) { 1590 return sProvider.apply(operations, this); 1591 } 1592 1593 private void undoLocal() { 1594 sProvider.undo(this); 1595 } 1596 1597 public void undo(final Context context, final Uri undoUri) { 1598 new Thread(new Runnable() { 1599 @Override 1600 public void run() { 1601 Cursor c = context.getContentResolver().query(undoUri, UIProvider.UNDO_PROJECTION, 1602 null, null, null); 1603 if (c != null) { 1604 c.close(); 1605 } 1606 } 1607 }).start(); 1608 undoLocal(); 1609 } 1610 1611 /** 1612 * Delete a group of conversations immediately in the UI and in a single transaction in the 1613 * underlying provider. See applyAction for argument descriptions 1614 */ 1615 public int delete(Context context, Collection<Conversation> conversations) { 1616 return applyAction(context, conversations, ConversationOperation.DELETE); 1617 } 1618 1619 /** 1620 * As above, for archive 1621 */ 1622 public int archive(Context context, Collection<Conversation> conversations) { 1623 return applyAction(context, conversations, ConversationOperation.ARCHIVE); 1624 } 1625 1626 /** 1627 * As above, for mute 1628 */ 1629 public int mute(Context context, Collection<Conversation> conversations) { 1630 return applyAction(context, conversations, ConversationOperation.MUTE); 1631 } 1632 1633 /** 1634 * As above, for report spam 1635 */ 1636 public int reportSpam(Context context, Collection<Conversation> conversations) { 1637 return applyAction(context, conversations, ConversationOperation.REPORT_SPAM); 1638 } 1639 1640 /** 1641 * As above, for mostly archive 1642 */ 1643 public int mostlyArchive(Context context, Collection<Conversation> conversations) { 1644 return applyAction(context, conversations, ConversationOperation.MOSTLY_ARCHIVE); 1645 } 1646 1647 /** 1648 * As above, for mostly delete 1649 */ 1650 public int mostlyDelete(Context context, Collection<Conversation> conversations) { 1651 return applyAction(context, conversations, ConversationOperation.MOSTLY_DELETE); 1652 } 1653 1654 /** 1655 * Convenience method for performing an operation on a group of conversations 1656 * @param context the caller's context 1657 * @param conversations the conversations to be affected 1658 * @param opAction the action to take 1659 * @return the sequence number of the operation applied in CC 1660 */ 1661 private int applyAction(Context context, Collection<Conversation> conversations, 1662 int opAction) { 1663 ArrayList<ConversationOperation> ops = Lists.newArrayList(); 1664 for (Conversation conv: conversations) { 1665 ConversationOperation op = 1666 new ConversationOperation(opAction, conv); 1667 ops.add(op); 1668 } 1669 return apply(context, ops); 1670 } 1671 1672}