ConversationCursor.java revision 4015c182ab04edaa7cd8b75490f4336348ec29da
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.ContentProviderResult;
24import android.content.ContentResolver;
25import android.content.ContentValues;
26import android.content.OperationApplicationException;
27import android.database.CharArrayBuffer;
28import android.database.ContentObserver;
29import android.database.Cursor;
30import android.database.DataSetObserver;
31import android.net.Uri;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.Looper;
35import android.os.RemoteException;
36import android.util.Log;
37
38import com.android.mail.providers.Conversation;
39import com.android.mail.providers.UIProvider;
40import com.android.mail.providers.UIProvider.ConversationColumns;
41
42import java.util.ArrayList;
43import java.util.HashMap;
44import java.util.Iterator;
45import java.util.List;
46
47/**
48 * ConversationCursor is a wrapper around a conversation list cursor that provides update/delete
49 * caching for quick UI response. This is effectively a singleton class, as the cache is
50 * implemented as a static HashMap.
51 */
52public final class ConversationCursor implements Cursor {
53    private static final String TAG = "ConversationCursor";
54    private static final boolean DEBUG = true;  // STOPSHIP Set to false before shipping
55
56    // The authority of our conversation provider (a forwarding provider)
57    // This string must match the declaration in AndroidManifest.xml
58    private static final String sAuthority = "com.android.mail.conversation.provider";
59
60    // The cursor instantiator's activity
61    private static Activity sActivity;
62    // The cursor underlying the caching cursor
63    private static Cursor sUnderlyingCursor;
64    // The new cursor obtained via a requery
65    private static Cursor sRequeryCursor;
66    // A mapping from Uri to updated ContentValues
67    private static HashMap<String, ContentValues> sCacheMap = new HashMap<String, ContentValues>();
68    // Cache map lock (will be used only very briefly - few ms at most)
69    private static Object sCacheMapLock = new Object();
70    // A deleted row is indicated by the presence of DELETED_COLUMN in the cache map
71    private static final String DELETED_COLUMN = "__deleted__";
72    // An row cached during a requery is indicated by the presence of REQUERY_COLUMN in the map
73    private static final String REQUERY_COLUMN = "__requery__";
74    // A sentinel value for the "index" of the deleted column; it's an int that is otherwise invalid
75    private static final int DELETED_COLUMN_INDEX = -1;
76    // The current conversation cursor
77    private static ConversationCursor sConversationCursor;
78    // The index of the Uri whose data is reflected in the cached row
79    // Updates/Deletes to this Uri are cached
80    private static int sUriColumnIndex;
81    // The listener registered for this cursor
82    private static ConversationListener sListener;
83    // The ConversationProvider instance
84    private static ConversationProvider sProvider;
85    // Set when we're in the middle of a requery of the underlying cursor
86    private static boolean sRequeryInProgress = false;
87
88    // Column names for this cursor
89    private final String[] mColumnNames;
90    // The resolver for the cursor instantiator's context
91    private static ContentResolver mResolver;
92    // An observer on the underlying cursor (so we can detect changes from outside the UI)
93    private final CursorObserver mCursorObserver;
94    // Whether our observer is currently registered with the underlying cursor
95    private boolean mCursorObserverRegistered = false;
96
97    // The current position of the cursor
98    private int mPosition = -1;
99    // The number of cached deletions from this cursor (used to quickly generate an accurate count)
100    private static int sDeletedCount = 0;
101
102    // Parameters passed to the underlying query
103    private static Uri qUri;
104    private static String[] qProjection;
105    private static String qSelection;
106    private static String[] qSelectionArgs;
107    private static String qSortOrder;
108
109    private ConversationCursor(Cursor cursor, Activity activity, String messageListColumn) {
110        sActivity = activity;
111        mResolver = activity.getContentResolver();
112        sConversationCursor = this;
113        sUnderlyingCursor = cursor;
114        mCursorObserver = new CursorObserver();
115        resetCursor(null);
116        mColumnNames = cursor.getColumnNames();
117        sUriColumnIndex = cursor.getColumnIndex(messageListColumn);
118        if (sUriColumnIndex < 0) {
119            throw new IllegalArgumentException("Cursor must include a message list column");
120        }
121    }
122
123    /**
124     * Create a ConversationCursor; this should be called by the ListActivity using that cursor
125     * @param activity the activity creating the cursor
126     * @param messageListColumn the column used for individual cursor items
127     * @param uri the query uri
128     * @param projection the query projecion
129     * @param selection the query selection
130     * @param selectionArgs the query selection args
131     * @param sortOrder the query sort order
132     * @return a ConversationCursor
133     */
134    public static ConversationCursor create(Activity activity, String messageListColumn, Uri uri,
135            String[] projection, String selection, String[] selectionArgs, String sortOrder) {
136        qUri = uri;
137        qProjection = projection;
138        qSelection = selection;
139        qSelectionArgs = selectionArgs;
140        qSortOrder = sortOrder;
141        Cursor cursor = activity.getContentResolver().query(uri, projection, selection,
142                selectionArgs, sortOrder);
143        return new ConversationCursor(cursor, activity, messageListColumn);
144    }
145
146    /**
147     * Return whether the uri string (message list uri) is in the underlying cursor
148     * @param uriString the uri string we're looking for
149     * @return true if the uri string is in the cursor; false otherwise
150     */
151    private boolean isInUnderlyingCursor(String uriString) {
152        sUnderlyingCursor.moveToPosition(-1);
153        while (sUnderlyingCursor.moveToNext()) {
154            if (uriString.equals(sUnderlyingCursor.getString(sUriColumnIndex))) {
155                return true;
156            }
157        }
158        return false;
159    }
160
161    /**
162     * Reset the cursor; this involves clearing out our cache map and resetting our various counts
163     * The cursor should be reset whenever we get fresh data from the underlying cursor. The cache
164     * is locked during the reset, which will block the UI, but for only a very short time
165     * (estimated at a few ms, but we can profile this; remember that the cache will usually
166     * be empty or have a few entries)
167     */
168    private void resetCursor(Cursor newCursor) {
169        // Temporary, log time for reset
170        long startTime = System.currentTimeMillis();
171        synchronized (sCacheMapLock) {
172            // Walk through the cache.  Here are the cases:
173            // 1) The entry isn't marked with REQUERY - remove it from the cache. If DELETED is
174            //    set, decrement the deleted count
175            // 2) The REQUERY entry is still in the UP
176            //    2a) The REQUERY entry isn't DELETED; we're good, and the client change will remain
177            //    (i.e. client wins, it's on its way to the UP)
178            //    2b) The REQUERY entry is DELETED; we're good (client change remains, it's on
179            //        its way to the UP)
180            // 3) the REQUERY was deleted on the server (sheesh; this would be bizarre timing!) -
181            //    we need to throw the item out of the cache
182            // So ... the only interesting case is #3, we need to look for remaining deleted items
183            // and see if they're still in the UP
184            Iterator<HashMap.Entry<String, ContentValues>> iter = sCacheMap.entrySet().iterator();
185            while (iter.hasNext()) {
186                HashMap.Entry<String, ContentValues> entry = iter.next();
187                ContentValues values = entry.getValue();
188                if (values.containsKey(REQUERY_COLUMN) && isInUnderlyingCursor(entry.getKey())) {
189                    // If we're in a requery and we're still around, remove the requery key
190                    // We're good here, the cached change (delete/update) is on its way to UP
191                    values.remove(REQUERY_COLUMN);
192                } else {
193                    // Keep the deleted count up-to-date; remove the cache entry
194                    if (values.containsKey(DELETED_COLUMN)) {
195                        sDeletedCount--;
196                    }
197                    // Remove the entry
198                    iter.remove();
199                }
200            }
201
202            // Swap cursor
203            if (newCursor != null) {
204                sUnderlyingCursor.close();
205                sUnderlyingCursor = newCursor;
206            }
207
208            mPosition = -1;
209            sUnderlyingCursor.moveToPosition(mPosition);
210            if (!mCursorObserverRegistered) {
211                sUnderlyingCursor.registerContentObserver(mCursorObserver);
212                mCursorObserverRegistered = true;
213            }
214        }
215        Log.d(TAG, "resetCache time: " + ((System.currentTimeMillis() - startTime)) + "ms");
216    }
217
218    /**
219     * Set the listener for this cursor; we'll notify it when our data changes
220     */
221    public void setListener(ConversationListener listener) {
222        sListener = listener;
223    }
224
225    /**
226     * Generate a forwarding Uri to ConversationProvider from an original Uri.  We do this by
227     * changing the authority to ours, but otherwise leaving the Uri intact.
228     * NOTE: This won't handle query parameters, so the functionality will need to be added if
229     * parameters are used in the future
230     * @param uri the uri
231     * @return a forwarding uri to ConversationProvider
232     */
233    private static String uriToCachingUriString (Uri uri) {
234        String provider = uri.getAuthority();
235        return uri.getScheme() + "://" + sAuthority + "/" + provider + uri.getPath();
236    }
237
238    /**
239     * Regenerate the original Uri from a forwarding (ConversationProvider) Uri
240     * NOTE: See note above for uriToCachingUri
241     * @param uri the forwarding Uri
242     * @return the original Uri
243     */
244    private static Uri uriFromCachingUri(Uri uri) {
245        List<String> path = uri.getPathSegments();
246        Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0));
247        for (int i = 1; i < path.size(); i++) {
248            builder.appendPath(path.get(i));
249        }
250        return builder.build();
251    }
252
253    /**
254     * Cache a column name/value pair for a given Uri
255     * @param uriString the Uri for which the column name/value pair applies
256     * @param columnName the column name
257     * @param value the value to be cached
258     */
259    private static void cacheValue(String uriString, String columnName, Object value) {
260        synchronized (sCacheMapLock) {
261            // Get the map for our uri
262            ContentValues map = sCacheMap.get(uriString);
263            // Create one if necessary
264            if (map == null) {
265                map = new ContentValues();
266                sCacheMap.put(uriString, map);
267            }
268            // If we're caching a deletion, add to our count
269            if ((columnName == DELETED_COLUMN) && (map.get(columnName) == null)) {
270                sDeletedCount++;
271                if (DEBUG) {
272                    Log.d(TAG, "Deleted " + uriString);
273                }
274            }
275            // ContentValues has no generic "put", so we must test.  For now, the only classes of
276            // values implemented are Boolean/Integer/String, though others are trivially added
277            if (value instanceof Boolean) {
278                map.put(columnName, ((Boolean) value).booleanValue() ? 1 : 0);
279            } else if (value instanceof Integer) {
280                map.put(columnName, (Integer) value);
281            } else if (value instanceof String) {
282                map.put(columnName, (String) value);
283            } else {
284                String cname = value.getClass().getName();
285                throw new IllegalArgumentException("Value class not compatible with cache: "
286                        + cname);
287            }
288            if (sRequeryInProgress) {
289                map.put(REQUERY_COLUMN, 1);
290            }
291            if (DEBUG && (columnName != DELETED_COLUMN)) {
292                Log.d(TAG, "Caching value for " + uriString + ": " + columnName);
293            }
294        }
295    }
296
297    /**
298     * Get the cached value for the provided column; we special case -1 as the "deleted" column
299     * @param columnIndex the index of the column whose cached value we want to retrieve
300     * @return the cached value for this column, or null if there is none
301     */
302    private Object getCachedValue(int columnIndex) {
303        String uri = sUnderlyingCursor.getString(sUriColumnIndex);
304        ContentValues uriMap = sCacheMap.get(uri);
305        if (uriMap != null) {
306            String columnName;
307            if (columnIndex == DELETED_COLUMN_INDEX) {
308                columnName = DELETED_COLUMN;
309            } else {
310                columnName = mColumnNames[columnIndex];
311            }
312            return uriMap.get(columnName);
313        }
314        return null;
315    }
316
317    /**
318     * When the underlying cursor changes, we want to alert the listener
319     */
320    private void underlyingChanged() {
321        if (sListener != null) {
322            if (mCursorObserverRegistered) {
323                sUnderlyingCursor.unregisterContentObserver(mCursorObserver);
324                mCursorObserverRegistered = false;
325            }
326            sListener.onRefreshRequired();
327        }
328    }
329
330    /**
331     * Put the refreshed cursor in place (called by the UI)
332     */
333    public void swapCursors() {
334        if (sRequeryCursor == null) {
335            throw new IllegalStateException("Can't swap cursors; no requery done");
336        }
337        resetCursor(sRequeryCursor);
338        sRequeryCursor = null;
339        sRequeryInProgress = false;
340    }
341
342    /**
343     * Cancel a refresh in progress
344     */
345    public void cancelRefresh() {
346        synchronized(sCacheMapLock) {
347            // Mark the requery closed
348            sRequeryInProgress = false;
349            // If we have the cursor, close it; otherwise, it will get closed when the query
350            // finishes (it checks sRequeryInProgress)
351            if (sRequeryCursor != null) {
352                sRequeryCursor.close();
353                sRequeryCursor = null;
354            }
355        }
356    }
357
358    /**
359     * Get a list of deletions from ConversationCursor to the refreshed cursor that hasn't yet
360     * been swapped into place; this allows the UI to animate these away if desired
361     * @return a list of positions deleted in ConversationCursor
362     */
363    public ArrayList<Integer> getRefreshDeletions () {
364        Cursor deviceCursor = sConversationCursor;
365        Cursor serverCursor = sRequeryCursor;
366        ArrayList<Integer> deleteList = new ArrayList<Integer>();
367        int serverCount = serverCursor.getCount();
368        int deviceCount = deviceCursor.getCount();
369        deviceCursor.moveToFirst();
370        serverCursor.moveToFirst();
371        while (serverCount > 0 || deviceCount > 0) {
372            if (serverCount == 0) {
373                for (; deviceCount > 0; deviceCount--)
374                    deleteList.add(deviceCursor.getPosition());
375                break;
376            } else if (deviceCount == 0) {
377                break;
378            }
379            long deviceMs = deviceCursor.getLong(UIProvider.CONVERSATION_DATE_RECEIVED_MS_COLUMN);
380            long serverMs = serverCursor.getLong(UIProvider.CONVERSATION_DATE_RECEIVED_MS_COLUMN);
381            String deviceUri = deviceCursor.getString(UIProvider.CONVERSATION_URI_COLUMN);
382            String serverUri = serverCursor.getString(UIProvider.CONVERSATION_URI_COLUMN);
383            deviceCursor.moveToNext();
384            serverCursor.moveToNext();
385            serverCount--;
386            deviceCount--;
387            if (serverMs == deviceMs) {
388                // Check for duplicates here; if our identical dates refer to different messages,
389                // we'll just quit here for now (at worst, this will cause a non-animating delete)
390                // My guess is that this happens VERY rarely, if at all
391                if (!deviceUri.equals(serverUri)) {
392                    // To do this right, we'd find all of the rows with the same ms (date), etc...
393                    //return deleteList;
394                }
395                continue;
396            } else if (deviceMs > serverMs) {
397                deleteList.add(deviceCursor.getPosition() - 1);
398                // Move back because we've already advanced cursor (that's why we subtract 1 above)
399                serverCount++;
400                serverCursor.moveToPrevious();
401            } else if (serverMs > deviceMs) {
402                // If we wanted to track insertions, we'd so so here
403                // Move back because we've already advanced cursor
404                deviceCount++;
405                deviceCursor.moveToPrevious();
406            }
407        }
408        Log.d(TAG, "Deletions: " + deleteList);
409        return deleteList;
410    }
411
412    /**
413     * When we get a requery from the UI, we'll do it, but also clear the cache. The listener is
414     * notified when the requery is complete
415     * NOTE: This will have to change, of course, when we start using loaders...
416     */
417    public boolean refresh() {
418        if (sRequeryInProgress) {
419            return false;
420        }
421        // Say we're starting a requery
422        sRequeryInProgress = true;
423        new Thread(new Runnable() {
424            @Override
425            public void run() {
426                // Get new data
427                sRequeryCursor =
428                        mResolver.query(qUri, qProjection, qSelection, qSelectionArgs, qSortOrder);
429                // Make sure window is full
430                synchronized(sCacheMapLock) {
431                    if (sRequeryInProgress) {
432                        sRequeryCursor.getCount();
433                        sActivity.runOnUiThread(new Runnable() {
434                            @Override
435                            public void run() {
436                                sListener.onRefreshReady();
437                            }});
438                    } else {
439                        cancelRefresh();
440                    }
441                }
442            }
443        }).start();
444        return true;
445    }
446
447    public void close() {
448        // Unregister our observer on the underlying cursor and close as usual
449        sUnderlyingCursor.unregisterContentObserver(mCursorObserver);
450        sUnderlyingCursor.close();
451    }
452
453    /**
454     * Move to the next not-deleted item in the conversation
455     */
456    public boolean moveToNext() {
457        while (true) {
458            boolean ret = sUnderlyingCursor.moveToNext();
459            if (!ret) return false;
460            if (getCachedValue(DELETED_COLUMN_INDEX) instanceof Integer) continue;
461            mPosition++;
462            return true;
463        }
464    }
465
466    /**
467     * Move to the previous not-deleted item in the conversation
468     */
469    public boolean moveToPrevious() {
470        while (true) {
471            boolean ret = sUnderlyingCursor.moveToPrevious();
472            if (!ret) return false;
473            if (getCachedValue(-1) instanceof Integer) continue;
474            mPosition--;
475            return true;
476        }
477    }
478
479    public int getPosition() {
480        return mPosition;
481    }
482
483    /**
484     * The actual cursor's count must be decremented by the number we've deleted from the UI
485     */
486    public int getCount() {
487        return sUnderlyingCursor.getCount() - sDeletedCount;
488    }
489
490    public boolean moveToFirst() {
491        sUnderlyingCursor.moveToPosition(-1);
492        mPosition = -1;
493        return moveToNext();
494    }
495
496    public boolean moveToPosition(int pos) {
497        if (pos == mPosition) return true;
498        if (pos > mPosition) {
499            while (pos > mPosition) {
500                if (!moveToNext()) {
501                    return false;
502                }
503            }
504            return true;
505        } else if (pos == 0) {
506            return moveToFirst();
507        } else {
508            while (pos < mPosition) {
509                if (!moveToPrevious()) {
510                    return false;
511                }
512            }
513            return true;
514        }
515    }
516
517    public boolean moveToLast() {
518        throw new UnsupportedOperationException("moveToLast unsupported!");
519    }
520
521    public boolean move(int offset) {
522        throw new UnsupportedOperationException("move unsupported!");
523    }
524
525    /**
526     * We need to override all of the getters to make sure they look at cached values before using
527     * the values in the underlying cursor
528     */
529    @Override
530    public double getDouble(int columnIndex) {
531        Object obj = getCachedValue(columnIndex);
532        if (obj != null) return (Double)obj;
533        return sUnderlyingCursor.getDouble(columnIndex);
534    }
535
536    @Override
537    public float getFloat(int columnIndex) {
538        Object obj = getCachedValue(columnIndex);
539        if (obj != null) return (Float)obj;
540        return sUnderlyingCursor.getFloat(columnIndex);
541    }
542
543    @Override
544    public int getInt(int columnIndex) {
545        Object obj = getCachedValue(columnIndex);
546        if (obj != null) return (Integer)obj;
547        return sUnderlyingCursor.getInt(columnIndex);
548    }
549
550    @Override
551    public long getLong(int columnIndex) {
552        Object obj = getCachedValue(columnIndex);
553        if (obj != null) return (Long)obj;
554        return sUnderlyingCursor.getLong(columnIndex);
555    }
556
557    @Override
558    public short getShort(int columnIndex) {
559        Object obj = getCachedValue(columnIndex);
560        if (obj != null) return (Short)obj;
561        return sUnderlyingCursor.getShort(columnIndex);
562    }
563
564    @Override
565    public String getString(int columnIndex) {
566        // If we're asking for the Uri for the conversation list, we return a forwarding URI
567        // so that we can intercept update/delete and handle it ourselves
568        if (columnIndex == sUriColumnIndex) {
569            Uri uri = Uri.parse(sUnderlyingCursor.getString(columnIndex));
570            return uriToCachingUriString(uri);
571        }
572        Object obj = getCachedValue(columnIndex);
573        if (obj != null) return (String)obj;
574        return sUnderlyingCursor.getString(columnIndex);
575    }
576
577    @Override
578    public byte[] getBlob(int columnIndex) {
579        Object obj = getCachedValue(columnIndex);
580        if (obj != null) return (byte[])obj;
581        return sUnderlyingCursor.getBlob(columnIndex);
582    }
583
584    /**
585     * Observer of changes to underlying data
586     */
587    private class CursorObserver extends ContentObserver {
588        public CursorObserver() {
589            super(new Handler());
590        }
591
592        @Override
593        public void onChange(boolean selfChange) {
594            // If we're here, then something outside of the UI has changed the data, and we
595            // must query the underlying provider for that data
596            if (DEBUG) {
597                Log.d(TAG, "Underlying conversation cursor changed; requerying");
598            }
599            // It's not at all obvious to me why we must unregister/re-register after the requery
600            // However, if we don't we'll only get one notification and no more...
601            ConversationCursor.this.underlyingChanged();
602        }
603    }
604
605    /**
606     * ConversationProvider is the ContentProvider for our forwarding Uri's; it passes queries
607     * and inserts directly, and caches updates/deletes before passing them through.  The caching
608     * will cause a redraw of the list with updated values.
609     */
610    public static class ConversationProvider extends ContentProvider {
611        public static final String AUTHORITY = sAuthority;
612
613        @Override
614        public boolean onCreate() {
615            sProvider = this;
616            return true;
617        }
618
619        @Override
620        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
621                String sortOrder) {
622            return mResolver.query(
623                    uriFromCachingUri(uri), projection, selection, selectionArgs, sortOrder);
624        }
625
626        @Override
627        public Uri insert(Uri uri, ContentValues values) {
628            insertLocal(uri, values);
629            return ProviderExecute.opInsert(uri, values);
630        }
631
632        @Override
633        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
634            updateLocal(uri, values);
635            return ProviderExecute.opUpdate(uri, values);
636        }
637
638        @Override
639        public int delete(Uri uri, String selection, String[] selectionArgs) {
640            deleteLocal(uri);
641            return ProviderExecute.opDelete(uri);
642        }
643
644        @Override
645        public String getType(Uri uri) {
646            return null;
647        }
648
649        /**
650         * Quick and dirty class that executes underlying provider CRUD operations on a background
651         * thread.
652         */
653        static class ProviderExecute implements Runnable {
654            static final int DELETE = 0;
655            static final int INSERT = 1;
656            static final int UPDATE = 2;
657
658            final int mCode;
659            final Uri mUri;
660            final ContentValues mValues; //HEHEH
661
662            ProviderExecute(int code, Uri uri, ContentValues values) {
663                mCode = code;
664                mUri = uriFromCachingUri(uri);
665                mValues = values;
666            }
667
668            ProviderExecute(int code, Uri uri) {
669                this(code, uri, null);
670            }
671
672            static Uri opInsert(Uri uri, ContentValues values) {
673                ProviderExecute e = new ProviderExecute(INSERT, uri, values);
674                if (offUiThread()) return (Uri)e.go();
675                new Thread(e).start();
676                return null;
677            }
678
679            static int opDelete(Uri uri) {
680                ProviderExecute e = new ProviderExecute(DELETE, uri);
681                if (offUiThread()) return (Integer)e.go();
682                new Thread(new ProviderExecute(DELETE, uri)).start();
683                return 0;
684            }
685
686            static int opUpdate(Uri uri, ContentValues values) {
687                ProviderExecute e = new ProviderExecute(UPDATE, uri, values);
688                if (offUiThread()) return (Integer)e.go();
689                new Thread(e).start();
690                return 0;
691            }
692
693            @Override
694            public void run() {
695                go();
696            }
697
698            public Object go() {
699                switch(mCode) {
700                    case DELETE:
701                        return mResolver.delete(mUri, null, null);
702                    case INSERT:
703                        return mResolver.insert(mUri, mValues);
704                    case UPDATE:
705                        return mResolver.update(mUri,  mValues, null, null);
706                    default:
707                        return null;
708                }
709            }
710        }
711
712        private void insertLocal(Uri uri, ContentValues values) {
713            // Placeholder for now; there's no local insert
714        }
715
716        private void deleteLocal(Uri uri) {
717            Uri underlyingUri = uriFromCachingUri(uri);
718            String uriString = underlyingUri.toString();
719            cacheValue(uriString, DELETED_COLUMN, true);
720        }
721
722        private void updateLocal(Uri uri, ContentValues values) {
723            Uri underlyingUri = uriFromCachingUri(uri);
724            // Remember to decode the underlying Uri as it might be encoded (as w/ Gmail)
725            String uriString =  Uri.decode(underlyingUri.toString());
726            for (String columnName: values.keySet()) {
727                cacheValue(uriString, columnName, values.get(columnName));
728            }
729        }
730
731        static boolean offUiThread() {
732            return Looper.getMainLooper().getThread() != Thread.currentThread();
733        }
734
735        public ContentProviderResult[] apply(ArrayList<ConversationOperation> ops) {
736            final HashMap<String, ArrayList<ContentProviderOperation>> batchMap =
737                    new HashMap<String, ArrayList<ContentProviderOperation>>();
738
739            // Execute locally and build CPO's for underlying provider
740            for (ConversationOperation op: ops) {
741                Uri underlyingUri = uriFromCachingUri(op.mUri);
742                String authority = underlyingUri.getAuthority();
743                ArrayList<ContentProviderOperation> authOps = batchMap.get(authority);
744                if (authOps == null) {
745                    authOps = new ArrayList<ContentProviderOperation>();
746                    batchMap.put(authority, authOps);
747                }
748                authOps.add(op.execute(underlyingUri));
749            }
750
751            // Send changes to underlying provider
752            for (String authority: batchMap.keySet()) {
753                try {
754                    if (offUiThread()) {
755                        return mResolver.applyBatch(authority, batchMap.get(authority));
756                    } else {
757                        final String auth = authority;
758                        new Thread(new Runnable() {
759                            @Override
760                            public void run() {
761                                try {
762                                    mResolver.applyBatch(auth, batchMap.get(auth));
763                                } catch (RemoteException e) {
764                                } catch (OperationApplicationException e) {
765                                }
766                           }
767                        }).start();
768                        return new ContentProviderResult[ops.size()];
769                    }
770                } catch (RemoteException e) {
771                } catch (OperationApplicationException e) {
772                }
773            }
774            // Need to put together the results; ugh, in order
775            return null;
776        }
777    }
778
779    /**
780     * ConversationOperation is the encapsulation of a ContentProvider operation to be performed
781     * atomically as part of a "batch" operation.
782     */
783    public static class ConversationOperation {
784        public static final int DELETE = 0;
785        public static final int INSERT = 1;
786        public static final int UPDATE = 2;
787
788        private final int mType;
789        private final Uri mUri;
790        private final ContentValues mValues;
791
792        public ConversationOperation(int type, Conversation conv) {
793            this(type, conv, null);
794        }
795
796        public ConversationOperation(int type, Conversation conv, ContentValues values) {
797            mType = type;
798            mUri = conv.messageListUri;
799            mValues = values;
800        }
801
802        private ContentProviderOperation execute(Uri underlyingUri) {
803            switch(mType) {
804                case DELETE:
805                    sProvider.deleteLocal(mUri);
806                    return ContentProviderOperation.newDelete(underlyingUri).build();
807                case UPDATE:
808                    sProvider.updateLocal(mUri, mValues);
809                    return ContentProviderOperation.newUpdate(underlyingUri)
810                            .withValues(mValues)
811                            .build();
812                case INSERT:
813                    sProvider.insertLocal(mUri, mValues);
814                    return ContentProviderOperation.newInsert(underlyingUri)
815                            .withValues(mValues).build();
816                default:
817                    throw new UnsupportedOperationException(
818                            "No such ConversationOperation type: " + mType);
819            }
820        }
821    }
822
823    /**
824     * For now, a single listener can be associated with the cursor, and for now we'll just
825     * notify on deletions
826     */
827    public interface ConversationListener {
828        // Data in the underlying provider has changed; a refresh is required to sync up
829        public void onRefreshRequired();
830        // We've completed a requested refresh of the underlying cursor
831        public void onRefreshReady();
832    }
833
834    @Override
835    public boolean isFirst() {
836        throw new UnsupportedOperationException();
837    }
838
839    @Override
840    public boolean isLast() {
841        throw new UnsupportedOperationException();
842    }
843
844    @Override
845    public boolean isBeforeFirst() {
846        throw new UnsupportedOperationException();
847    }
848
849    @Override
850    public boolean isAfterLast() {
851        throw new UnsupportedOperationException();
852    }
853
854    @Override
855    public int getColumnIndex(String columnName) {
856        return sUnderlyingCursor.getColumnIndex(columnName);
857    }
858
859    @Override
860    public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
861        return sUnderlyingCursor.getColumnIndexOrThrow(columnName);
862    }
863
864    @Override
865    public String getColumnName(int columnIndex) {
866        return sUnderlyingCursor.getColumnName(columnIndex);
867    }
868
869    @Override
870    public String[] getColumnNames() {
871        return sUnderlyingCursor.getColumnNames();
872    }
873
874    @Override
875    public int getColumnCount() {
876        return sUnderlyingCursor.getColumnCount();
877    }
878
879    @Override
880    public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) {
881        throw new UnsupportedOperationException();
882    }
883
884    @Override
885    public int getType(int columnIndex) {
886        return sUnderlyingCursor.getType(columnIndex);
887    }
888
889    @Override
890    public boolean isNull(int columnIndex) {
891        throw new UnsupportedOperationException();
892    }
893
894    @Override
895    public void deactivate() {
896        throw new UnsupportedOperationException();
897    }
898
899    @Override
900    public boolean isClosed() {
901        return sUnderlyingCursor.isClosed();
902    }
903
904    @Override
905    public void registerContentObserver(ContentObserver observer) {
906    }
907
908    @Override
909    public void unregisterContentObserver(ContentObserver observer) {
910    }
911
912    @Override
913    public void registerDataSetObserver(DataSetObserver observer) {
914    }
915
916    @Override
917    public void unregisterDataSetObserver(DataSetObserver observer) {
918    }
919
920    @Override
921    public void setNotificationUri(ContentResolver cr, Uri uri) {
922        throw new UnsupportedOperationException();
923    }
924
925    @Override
926    public boolean getWantsAllOnMoveCalls() {
927        throw new UnsupportedOperationException();
928    }
929
930    @Override
931    public Bundle getExtras() {
932        throw new UnsupportedOperationException();
933    }
934
935    @Override
936    public Bundle respond(Bundle extras) {
937        throw new UnsupportedOperationException();
938    }
939
940    @Override
941    public boolean requery() {
942        return true;
943    }
944}
945