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