BaseRecipientAdapter.java revision f7e202d8b83bfbd73ca47ba7843ebc4dd57c2fa4
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.ex.chips;
18
19import android.accounts.Account;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.pm.PackageManager;
23import android.content.pm.PackageManager.NameNotFoundException;
24import android.content.res.Resources;
25import android.database.Cursor;
26import android.graphics.Bitmap;
27import android.graphics.BitmapFactory;
28import android.net.Uri;
29import android.os.AsyncTask;
30import android.os.Handler;
31import android.os.Message;
32import android.provider.ContactsContract;
33import android.provider.ContactsContract.CommonDataKinds.Photo;
34import android.provider.ContactsContract.Directory;
35import android.text.TextUtils;
36import android.text.util.Rfc822Token;
37import android.util.Log;
38import android.util.LruCache;
39import android.view.LayoutInflater;
40import android.view.View;
41import android.view.ViewGroup;
42import android.widget.AutoCompleteTextView;
43import android.widget.BaseAdapter;
44import android.widget.Filter;
45import android.widget.Filterable;
46import android.widget.ImageView;
47import android.widget.TextView;
48
49import java.util.ArrayList;
50import java.util.HashSet;
51import java.util.LinkedHashMap;
52import java.util.List;
53import java.util.Map;
54import java.util.Set;
55
56/**
57 * Adapter for showing a recipient list.
58 */
59public abstract class BaseRecipientAdapter extends BaseAdapter implements Filterable,
60        AccountSpecifier {
61    private static final String TAG = "BaseRecipientAdapter";
62
63    private static final boolean DEBUG = false;
64
65    /**
66     * The preferred number of results to be retrieved. This number may be
67     * exceeded if there are several directories configured, because we will use
68     * the same limit for all directories.
69     */
70    private static final int DEFAULT_PREFERRED_MAX_RESULT_COUNT = 10;
71
72    /**
73     * The number of extra entries requested to allow for duplicates. Duplicates
74     * are removed from the overall result.
75     */
76    static final int ALLOWANCE_FOR_DUPLICATES = 5;
77
78    // This is ContactsContract.PRIMARY_ACCOUNT_NAME. Available from ICS as hidden
79    static final String PRIMARY_ACCOUNT_NAME = "name_for_primary_account";
80    // This is ContactsContract.PRIMARY_ACCOUNT_TYPE. Available from ICS as hidden
81    static final String PRIMARY_ACCOUNT_TYPE = "type_for_primary_account";
82
83    /** The number of photos cached in this Adapter. */
84    private static final int PHOTO_CACHE_SIZE = 20;
85
86    /**
87     * The "Waiting for more contacts" message will be displayed if search is not complete
88     * within this many milliseconds.
89     */
90    private static final int MESSAGE_SEARCH_PENDING_DELAY = 1000;
91    /** Used to prepare "Waiting for more contacts" message. */
92    private static final int MESSAGE_SEARCH_PENDING = 1;
93
94    public static final int QUERY_TYPE_EMAIL = 0;
95    public static final int QUERY_TYPE_PHONE = 1;
96
97    private final Queries.Query mQuery;
98    private final int mQueryType;
99
100    /**
101     * Model object for a {@link Directory} row.
102     */
103    public final static class DirectorySearchParams {
104        public long directoryId;
105        public String directoryType;
106        public String displayName;
107        public String accountName;
108        public String accountType;
109        public CharSequence constraint;
110        public DirectoryFilter filter;
111    }
112
113    private static class PhotoQuery {
114        public static final String[] PROJECTION = {
115            Photo.PHOTO
116        };
117
118        public static final int PHOTO = 0;
119    }
120
121    protected static class DirectoryListQuery {
122
123        public static final Uri URI =
124                Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "directories");
125        public static final String[] PROJECTION = {
126            Directory._ID,              // 0
127            Directory.ACCOUNT_NAME,     // 1
128            Directory.ACCOUNT_TYPE,     // 2
129            Directory.DISPLAY_NAME,     // 3
130            Directory.PACKAGE_NAME,     // 4
131            Directory.TYPE_RESOURCE_ID, // 5
132        };
133
134        public static final int ID = 0;
135        public static final int ACCOUNT_NAME = 1;
136        public static final int ACCOUNT_TYPE = 2;
137        public static final int DISPLAY_NAME = 3;
138        public static final int PACKAGE_NAME = 4;
139        public static final int TYPE_RESOURCE_ID = 5;
140    }
141
142    /** Used to temporarily hold results in Cursor objects. */
143    private static class TemporaryEntry {
144        public final String displayName;
145        public final String destination;
146        public final int destinationType;
147        public final String destinationLabel;
148        public final long contactId;
149        public final long dataId;
150        public final String thumbnailUriString;
151        public final int displayNameSource;
152
153        public TemporaryEntry(Cursor cursor) {
154            this.displayName = cursor.getString(Queries.Query.NAME);
155            this.destination = cursor.getString(Queries.Query.DESTINATION);
156            this.destinationType = cursor.getInt(Queries.Query.DESTINATION_TYPE);
157            this.destinationLabel = cursor.getString(Queries.Query.DESTINATION_LABEL);
158            this.contactId = cursor.getLong(Queries.Query.CONTACT_ID);
159            this.dataId = cursor.getLong(Queries.Query.DATA_ID);
160            this.thumbnailUriString = cursor.getString(Queries.Query.PHOTO_THUMBNAIL_URI);
161            this.displayNameSource = cursor.getInt(Queries.Query.DISPLAY_NAME_SOURCE);
162        }
163    }
164
165    /**
166     * Used to pass results from {@link DefaultFilter#performFiltering(CharSequence)} to
167     * {@link DefaultFilter#publishResults(CharSequence, android.widget.Filter.FilterResults)}
168     */
169    private static class DefaultFilterResult {
170        public final List<RecipientEntry> entries;
171        public final LinkedHashMap<Long, List<RecipientEntry>> entryMap;
172        public final List<RecipientEntry> nonAggregatedEntries;
173        public final Set<String> existingDestinations;
174        public final List<DirectorySearchParams> paramsList;
175
176        public DefaultFilterResult(List<RecipientEntry> entries,
177                LinkedHashMap<Long, List<RecipientEntry>> entryMap,
178                List<RecipientEntry> nonAggregatedEntries,
179                Set<String> existingDestinations,
180                List<DirectorySearchParams> paramsList) {
181            this.entries = entries;
182            this.entryMap = entryMap;
183            this.nonAggregatedEntries = nonAggregatedEntries;
184            this.existingDestinations = existingDestinations;
185            this.paramsList = paramsList;
186        }
187    }
188
189    /**
190     * An asynchronous filter used for loading two data sets: email rows from the local
191     * contact provider and the list of {@link Directory}'s.
192     */
193    private final class DefaultFilter extends Filter {
194
195        @Override
196        protected FilterResults performFiltering(CharSequence constraint) {
197            if (DEBUG) {
198                Log.d(TAG, "start filtering. constraint: " + constraint + ", thread:"
199                        + Thread.currentThread());
200            }
201
202            final FilterResults results = new FilterResults();
203            Cursor defaultDirectoryCursor = null;
204            Cursor directoryCursor = null;
205
206            if (TextUtils.isEmpty(constraint)) {
207                clearTempEntries();
208                // Return empty results.
209                return results;
210            }
211
212            try {
213                defaultDirectoryCursor = doQuery(constraint, mPreferredMaxResultCount, null);
214
215                if (defaultDirectoryCursor == null) {
216                    if (DEBUG) {
217                        Log.w(TAG, "null cursor returned for default Email filter query.");
218                    }
219                } else {
220                    // These variables will become mEntries, mEntryMap, mNonAggregatedEntries, and
221                    // mExistingDestinations. Here we shouldn't use those member variables directly
222                    // since this method is run outside the UI thread.
223                    final LinkedHashMap<Long, List<RecipientEntry>> entryMap =
224                            new LinkedHashMap<Long, List<RecipientEntry>>();
225                    final List<RecipientEntry> nonAggregatedEntries =
226                            new ArrayList<RecipientEntry>();
227                    final Set<String> existingDestinations = new HashSet<String>();
228
229                    while (defaultDirectoryCursor.moveToNext()) {
230                        // Note: At this point each entry doesn't contain any photo
231                        // (thus getPhotoBytes() returns null).
232                        putOneEntry(new TemporaryEntry(defaultDirectoryCursor),
233                                true, entryMap, nonAggregatedEntries, existingDestinations);
234                    }
235
236                    // We'll copy this result to mEntry in publicResults() (run in the UX thread).
237                    final List<RecipientEntry> entries = constructEntryList(
238                            entryMap, nonAggregatedEntries);
239
240                    // After having local results, check the size of results. If the results are
241                    // not enough, we search remote directories, which will take longer time.
242                    final int limit = mPreferredMaxResultCount - existingDestinations.size();
243                    final List<DirectorySearchParams> paramsList;
244                    if (limit > 0) {
245                        if (DEBUG) {
246                            Log.d(TAG, "More entries should be needed (current: "
247                                    + existingDestinations.size()
248                                    + ", remaining limit: " + limit + ") ");
249                        }
250                        directoryCursor = mContentResolver.query(
251                                DirectoryListQuery.URI, DirectoryListQuery.PROJECTION,
252                                null, null, null);
253                        paramsList = setupOtherDirectories(mContext, directoryCursor, mAccount);
254                    } else {
255                        // We don't need to search other directories.
256                        paramsList = null;
257                    }
258
259                    results.values = new DefaultFilterResult(
260                            entries, entryMap, nonAggregatedEntries,
261                            existingDestinations, paramsList);
262                    results.count = 1;
263                }
264            } finally {
265                if (defaultDirectoryCursor != null) {
266                    defaultDirectoryCursor.close();
267                }
268                if (directoryCursor != null) {
269                    directoryCursor.close();
270                }
271            }
272            return results;
273        }
274
275        @Override
276        protected void publishResults(final CharSequence constraint, FilterResults results) {
277            // If a user types a string very quickly and database is slow, "constraint" refers to
278            // an older text which shows inconsistent results for users obsolete (b/4998713).
279            // TODO: Fix it.
280            mCurrentConstraint = constraint;
281
282            clearTempEntries();
283
284            if (results.values != null) {
285                DefaultFilterResult defaultFilterResult = (DefaultFilterResult) results.values;
286                mEntryMap = defaultFilterResult.entryMap;
287                mNonAggregatedEntries = defaultFilterResult.nonAggregatedEntries;
288                mExistingDestinations = defaultFilterResult.existingDestinations;
289
290                // If there are no local results, in the new result set, cache off what had been
291                // shown to the user for use until the first directory result is returned
292                if (defaultFilterResult.entries.size() == 0 &&
293                        defaultFilterResult.paramsList != null) {
294                    cacheCurrentEntries();
295                }
296
297                updateEntries(defaultFilterResult.entries);
298
299                // We need to search other remote directories, doing other Filter requests.
300                if (defaultFilterResult.paramsList != null) {
301                    final int limit = mPreferredMaxResultCount -
302                            defaultFilterResult.existingDestinations.size();
303                    startSearchOtherDirectories(constraint, defaultFilterResult.paramsList, limit);
304                }
305            }
306
307        }
308
309        @Override
310        public CharSequence convertResultToString(Object resultValue) {
311            final RecipientEntry entry = (RecipientEntry)resultValue;
312            final String displayName = entry.getDisplayName();
313            final String emailAddress = entry.getDestination();
314            if (TextUtils.isEmpty(displayName) || TextUtils.equals(displayName, emailAddress)) {
315                 return emailAddress;
316            } else {
317                return new Rfc822Token(displayName, emailAddress, null).toString();
318            }
319        }
320    }
321
322    /**
323     * An asynchronous filter that performs search in a particular directory.
324     */
325    private final class DirectoryFilter extends Filter {
326        private final DirectorySearchParams mParams;
327        private int mLimit;
328
329        public DirectoryFilter(DirectorySearchParams params) {
330            mParams = params;
331        }
332
333        public synchronized void setLimit(int limit) {
334            this.mLimit = limit;
335        }
336
337        public synchronized int getLimit() {
338            return this.mLimit;
339        }
340
341        @Override
342        protected FilterResults performFiltering(CharSequence constraint) {
343            if (DEBUG) {
344                Log.d(TAG, "DirectoryFilter#performFiltering. directoryId: " + mParams.directoryId
345                        + ", constraint: " + constraint + ", thread: " + Thread.currentThread());
346            }
347            final FilterResults results = new FilterResults();
348            results.values = null;
349            results.count = 0;
350
351            if (!TextUtils.isEmpty(constraint)) {
352                final ArrayList<TemporaryEntry> tempEntries = new ArrayList<TemporaryEntry>();
353
354                Cursor cursor = null;
355                try {
356                    // We don't want to pass this Cursor object to UI thread (b/5017608).
357                    // Assuming the result should contain fairly small results (at most ~10),
358                    // We just copy everything to local structure.
359                    cursor = doQuery(constraint, getLimit(), mParams.directoryId);
360
361                    if (cursor != null) {
362                        while (cursor.moveToNext()) {
363                            tempEntries.add(new TemporaryEntry(cursor));
364                        }
365                    }
366                } finally {
367                    if (cursor != null) {
368                        cursor.close();
369                    }
370                }
371                if (!tempEntries.isEmpty()) {
372                    results.values = tempEntries;
373                    results.count = 1;
374                }
375            }
376
377            if (DEBUG) {
378                Log.v(TAG, "finished loading directory \"" + mParams.displayName + "\"" +
379                        " with query " + constraint);
380            }
381
382            return results;
383        }
384
385        @Override
386        protected void publishResults(final CharSequence constraint, FilterResults results) {
387            if (DEBUG) {
388                Log.d(TAG, "DirectoryFilter#publishResult. constraint: " + constraint
389                        + ", mCurrentConstraint: " + mCurrentConstraint);
390            }
391            mDelayedMessageHandler.removeDelayedLoadMessage();
392            // Check if the received result matches the current constraint
393            // If not - the user must have continued typing after the request was issued, which
394            // means several member variables (like mRemainingDirectoryLoad) are already
395            // overwritten so shouldn't be touched here anymore.
396            if (TextUtils.equals(constraint, mCurrentConstraint)) {
397                if (results.count > 0) {
398                    @SuppressWarnings("unchecked")
399                    final ArrayList<TemporaryEntry> tempEntries =
400                            (ArrayList<TemporaryEntry>) results.values;
401
402                    for (TemporaryEntry tempEntry : tempEntries) {
403                        putOneEntry(tempEntry, mParams.directoryId == Directory.DEFAULT,
404                                mEntryMap, mNonAggregatedEntries, mExistingDestinations);
405                    }
406                }
407
408                // If there are remaining directories, set up delayed message again.
409                mRemainingDirectoryCount--;
410                if (mRemainingDirectoryCount > 0) {
411                    if (DEBUG) {
412                        Log.d(TAG, "Resend delayed load message. Current mRemainingDirectoryLoad: "
413                                + mRemainingDirectoryCount);
414                    }
415                    mDelayedMessageHandler.sendDelayedLoadMessage();
416                }
417
418                // If this directory result has some items, or there are no more directories that
419                // we are waiting for, clear the temp results
420                if (results.count > 0 || mRemainingDirectoryCount == 0) {
421                    // Clear the temp entries
422                    clearTempEntries();
423                }
424            }
425
426            // Show the list again without "waiting" message.
427            updateEntries(constructEntryList(mEntryMap, mNonAggregatedEntries));
428        }
429    }
430
431    private final Context mContext;
432    private final ContentResolver mContentResolver;
433    private final LayoutInflater mInflater;
434    private Account mAccount;
435    private final int mPreferredMaxResultCount;
436    private final Handler mHandler = new Handler();
437
438    /**
439     * {@link #mEntries} is responsible for showing every result for this Adapter. To
440     * construct it, we use {@link #mEntryMap}, {@link #mNonAggregatedEntries}, and
441     * {@link #mExistingDestinations}.
442     *
443     * First, each destination (an email address or a phone number) with a valid contactId is
444     * inserted into {@link #mEntryMap} and grouped by the contactId. Destinations without valid
445     * contactId (possible if they aren't in local storage) are stored in
446     * {@link #mNonAggregatedEntries}.
447     * Duplicates are removed using {@link #mExistingDestinations}.
448     *
449     * After having all results from Cursor objects, all destinations in mEntryMap are copied to
450     * {@link #mEntries}. If the number of destinations is not enough (i.e. less than
451     * {@link #mPreferredMaxResultCount}), destinations in mNonAggregatedEntries are also used.
452     *
453     * These variables are only used in UI thread, thus should not be touched in
454     * performFiltering() methods.
455     */
456    private LinkedHashMap<Long, List<RecipientEntry>> mEntryMap;
457    private List<RecipientEntry> mNonAggregatedEntries;
458    private Set<String> mExistingDestinations;
459    /** Note: use {@link #updateEntries(List)} to update this variable. */
460    private List<RecipientEntry> mEntries;
461    private List<RecipientEntry> mTempEntries;
462
463    /** The number of directories this adapter is waiting for results. */
464    private int mRemainingDirectoryCount;
465
466    /**
467     * Used to ignore asynchronous queries with a different constraint, which may happen when
468     * users type characters quickly.
469     */
470    private CharSequence mCurrentConstraint;
471
472    private final LruCache<Uri, byte[]> mPhotoCacheMap;
473
474    /**
475     * Handler specific for maintaining "Waiting for more contacts" message, which will be shown
476     * when:
477     * - there are directories to be searched
478     * - results from directories are slow to come
479     */
480    private final class DelayedMessageHandler extends Handler {
481        @Override
482        public void handleMessage(Message msg) {
483            if (mRemainingDirectoryCount > 0) {
484                updateEntries(constructEntryList(mEntryMap, mNonAggregatedEntries));
485            }
486        }
487
488        public void sendDelayedLoadMessage() {
489            sendMessageDelayed(obtainMessage(MESSAGE_SEARCH_PENDING, 0, 0, null),
490                    MESSAGE_SEARCH_PENDING_DELAY);
491        }
492
493        public void removeDelayedLoadMessage() {
494            removeMessages(MESSAGE_SEARCH_PENDING);
495        }
496    }
497
498    private final DelayedMessageHandler mDelayedMessageHandler = new DelayedMessageHandler();
499
500    private EntriesUpdatedObserver mEntriesUpdatedObserver;
501
502    /**
503     * Constructor for email queries.
504     */
505    public BaseRecipientAdapter(Context context) {
506        this(context, DEFAULT_PREFERRED_MAX_RESULT_COUNT, QUERY_TYPE_EMAIL);
507    }
508
509    public BaseRecipientAdapter(Context context, int preferredMaxResultCount) {
510        this(context, preferredMaxResultCount, QUERY_TYPE_EMAIL);
511    }
512
513    public BaseRecipientAdapter(int queryMode, Context context) {
514        this(context, DEFAULT_PREFERRED_MAX_RESULT_COUNT, queryMode);
515    }
516
517    public BaseRecipientAdapter(int queryMode, Context context, int preferredMaxResultCount) {
518        this(context, preferredMaxResultCount, queryMode);
519    }
520
521    public BaseRecipientAdapter(Context context, int preferredMaxResultCount, int queryMode) {
522        mContext = context;
523        mContentResolver = context.getContentResolver();
524        mInflater = LayoutInflater.from(context);
525        mPreferredMaxResultCount = preferredMaxResultCount;
526        mPhotoCacheMap = new LruCache<Uri, byte[]>(PHOTO_CACHE_SIZE);
527        mQueryType = queryMode;
528
529        if (queryMode == QUERY_TYPE_EMAIL) {
530            mQuery = Queries.EMAIL;
531        } else if (queryMode == QUERY_TYPE_PHONE) {
532            mQuery = Queries.PHONE;
533        } else {
534            mQuery = Queries.EMAIL;
535            Log.e(TAG, "Unsupported query type: " + queryMode);
536        }
537    }
538
539    public int getQueryType() {
540        return mQueryType;
541    }
542
543    /**
544     * Set the account when known. Causes the search to prioritize contacts from that account.
545     */
546    @Override
547    public void setAccount(Account account) {
548        mAccount = account;
549    }
550
551    /** Will be called from {@link AutoCompleteTextView} to prepare auto-complete list. */
552    @Override
553    public Filter getFilter() {
554        return new DefaultFilter();
555    }
556
557    public static List<DirectorySearchParams> setupOtherDirectories(Context context,
558            Cursor directoryCursor, Account account) {
559        final PackageManager packageManager = context.getPackageManager();
560        final List<DirectorySearchParams> paramsList = new ArrayList<DirectorySearchParams>();
561        DirectorySearchParams preferredDirectory = null;
562        while (directoryCursor.moveToNext()) {
563            final long id = directoryCursor.getLong(DirectoryListQuery.ID);
564
565            // Skip the local invisible directory, because the default directory already includes
566            // all local results.
567            if (id == Directory.LOCAL_INVISIBLE) {
568                continue;
569            }
570
571            final DirectorySearchParams params = new DirectorySearchParams();
572            final String packageName = directoryCursor.getString(DirectoryListQuery.PACKAGE_NAME);
573            final int resourceId = directoryCursor.getInt(DirectoryListQuery.TYPE_RESOURCE_ID);
574            params.directoryId = id;
575            params.displayName = directoryCursor.getString(DirectoryListQuery.DISPLAY_NAME);
576            params.accountName = directoryCursor.getString(DirectoryListQuery.ACCOUNT_NAME);
577            params.accountType = directoryCursor.getString(DirectoryListQuery.ACCOUNT_TYPE);
578            if (packageName != null && resourceId != 0) {
579                try {
580                    final Resources resources =
581                            packageManager.getResourcesForApplication(packageName);
582                    params.directoryType = resources.getString(resourceId);
583                    if (params.directoryType == null) {
584                        Log.e(TAG, "Cannot resolve directory name: "
585                                + resourceId + "@" + packageName);
586                    }
587                } catch (NameNotFoundException e) {
588                    Log.e(TAG, "Cannot resolve directory name: "
589                            + resourceId + "@" + packageName, e);
590                }
591            }
592
593            // If an account has been provided and we found a directory that
594            // corresponds to that account, place that directory second, directly
595            // underneath the local contacts.
596            if (account != null && account.name.equals(params.accountName) &&
597                    account.type.equals(params.accountType)) {
598                preferredDirectory = params;
599            } else {
600                paramsList.add(params);
601            }
602        }
603
604        if (preferredDirectory != null) {
605            paramsList.add(1, preferredDirectory);
606        }
607
608        return paramsList;
609    }
610
611    /**
612     * Starts search in other directories using {@link Filter}. Results will be handled in
613     * {@link DirectoryFilter}.
614     */
615    private void startSearchOtherDirectories(
616            CharSequence constraint, List<DirectorySearchParams> paramsList, int limit) {
617        final int count = paramsList.size();
618        // Note: skipping the default partition (index 0), which has already been loaded
619        for (int i = 1; i < count; i++) {
620            final DirectorySearchParams params = paramsList.get(i);
621            params.constraint = constraint;
622            if (params.filter == null) {
623                params.filter = new DirectoryFilter(params);
624            }
625            params.filter.setLimit(limit);
626            params.filter.filter(constraint);
627        }
628
629        // Directory search started. We may show "waiting" message if directory results are slow
630        // enough.
631        mRemainingDirectoryCount = count - 1;
632        mDelayedMessageHandler.sendDelayedLoadMessage();
633    }
634
635    private static void putOneEntry(TemporaryEntry entry, boolean isAggregatedEntry,
636            LinkedHashMap<Long, List<RecipientEntry>> entryMap,
637            List<RecipientEntry> nonAggregatedEntries,
638            Set<String> existingDestinations) {
639        if (existingDestinations.contains(entry.destination)) {
640            return;
641        }
642
643        existingDestinations.add(entry.destination);
644
645        if (!isAggregatedEntry) {
646            nonAggregatedEntries.add(RecipientEntry.constructTopLevelEntry(
647                    entry.displayName,
648                    entry.displayNameSource,
649                    entry.destination, entry.destinationType, entry.destinationLabel,
650                    entry.contactId, entry.dataId, entry.thumbnailUriString, true));
651        } else if (entryMap.containsKey(entry.contactId)) {
652            // We already have a section for the person.
653            final List<RecipientEntry> entryList = entryMap.get(entry.contactId);
654            entryList.add(RecipientEntry.constructSecondLevelEntry(
655                    entry.displayName,
656                    entry.displayNameSource,
657                    entry.destination, entry.destinationType, entry.destinationLabel,
658                    entry.contactId, entry.dataId, entry.thumbnailUriString, true));
659        } else {
660            final List<RecipientEntry> entryList = new ArrayList<RecipientEntry>();
661            entryList.add(RecipientEntry.constructTopLevelEntry(
662                    entry.displayName,
663                    entry.displayNameSource,
664                    entry.destination, entry.destinationType, entry.destinationLabel,
665                    entry.contactId, entry.dataId, entry.thumbnailUriString, true));
666            entryMap.put(entry.contactId, entryList);
667        }
668    }
669
670    /**
671     * Constructs an actual list for this Adapter using {@link #mEntryMap}. Also tries to
672     * fetch a cached photo for each contact entry (other than separators), or request another
673     * thread to get one from directories.
674     */
675    private List<RecipientEntry> constructEntryList(
676            LinkedHashMap<Long, List<RecipientEntry>> entryMap,
677            List<RecipientEntry> nonAggregatedEntries) {
678        final List<RecipientEntry> entries = new ArrayList<RecipientEntry>();
679        int validEntryCount = 0;
680        for (Map.Entry<Long, List<RecipientEntry>> mapEntry : entryMap.entrySet()) {
681            final List<RecipientEntry> entryList = mapEntry.getValue();
682            final int size = entryList.size();
683            for (int i = 0; i < size; i++) {
684                RecipientEntry entry = entryList.get(i);
685                entries.add(entry);
686                tryFetchPhoto(entry);
687                validEntryCount++;
688            }
689            if (validEntryCount > mPreferredMaxResultCount) {
690                break;
691            }
692        }
693        if (validEntryCount <= mPreferredMaxResultCount) {
694            for (RecipientEntry entry : nonAggregatedEntries) {
695                if (validEntryCount > mPreferredMaxResultCount) {
696                    break;
697                }
698                entries.add(entry);
699                tryFetchPhoto(entry);
700
701                validEntryCount++;
702            }
703        }
704
705        return entries;
706    }
707
708
709    protected interface EntriesUpdatedObserver {
710        public void onChanged(List<RecipientEntry> entries);
711    }
712
713    public void registerUpdateObserver(EntriesUpdatedObserver observer) {
714        mEntriesUpdatedObserver = observer;
715    }
716
717    /** Resets {@link #mEntries} and notify the event to its parent ListView. */
718    private void updateEntries(List<RecipientEntry> newEntries) {
719        mEntries = newEntries;
720        mEntriesUpdatedObserver.onChanged(newEntries);
721        notifyDataSetChanged();
722    }
723
724    private void cacheCurrentEntries() {
725        mTempEntries = mEntries;
726    }
727
728    private void clearTempEntries() {
729        mTempEntries = null;
730    }
731
732    private List<RecipientEntry> getEntries() {
733        return mTempEntries != null ? mTempEntries : mEntries;
734    }
735
736    private void tryFetchPhoto(final RecipientEntry entry) {
737        final Uri photoThumbnailUri = entry.getPhotoThumbnailUri();
738        if (photoThumbnailUri != null) {
739            final byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
740            if (photoBytes != null) {
741                entry.setPhotoBytes(photoBytes);
742                // notifyDataSetChanged() should be called by a caller.
743            } else {
744                if (DEBUG) {
745                    Log.d(TAG, "No photo cache for " + entry.getDisplayName()
746                            + ". Fetch one asynchronously");
747                }
748                fetchPhotoAsync(entry, photoThumbnailUri);
749            }
750        }
751    }
752
753    private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
754        final AsyncTask<Void, Void, Void> photoLoadTask = new AsyncTask<Void, Void, Void>() {
755            @Override
756            protected Void doInBackground(Void... params) {
757                final Cursor photoCursor = mContentResolver.query(
758                        photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null);
759                if (photoCursor != null) {
760                    try {
761                        if (photoCursor.moveToFirst()) {
762                            final byte[] photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
763                            entry.setPhotoBytes(photoBytes);
764
765                            mHandler.post(new Runnable() {
766                                @Override
767                                public void run() {
768                                    mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
769                                    notifyDataSetChanged();
770                                }
771                            });
772                        }
773                    } finally {
774                        photoCursor.close();
775                    }
776                }
777                return null;
778            }
779        };
780        photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
781    }
782
783    protected void fetchPhoto(final RecipientEntry entry, final Uri photoThumbnailUri) {
784        byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
785        if (photoBytes != null) {
786            entry.setPhotoBytes(photoBytes);
787            return;
788        }
789        final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION,
790                null, null, null);
791        if (photoCursor != null) {
792            try {
793                if (photoCursor.moveToFirst()) {
794                    photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
795                    entry.setPhotoBytes(photoBytes);
796                    mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
797                }
798            } finally {
799                photoCursor.close();
800            }
801        }
802    }
803
804    private Cursor doQuery(CharSequence constraint, int limit, Long directoryId) {
805        final Uri.Builder builder = mQuery.getContentFilterUri().buildUpon()
806                .appendPath(constraint.toString())
807                .appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY,
808                        String.valueOf(limit + ALLOWANCE_FOR_DUPLICATES));
809        if (directoryId != null) {
810            builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
811                    String.valueOf(directoryId));
812        }
813        if (mAccount != null) {
814            builder.appendQueryParameter(PRIMARY_ACCOUNT_NAME, mAccount.name);
815            builder.appendQueryParameter(PRIMARY_ACCOUNT_TYPE, mAccount.type);
816        }
817        final long start = System.currentTimeMillis();
818        final Cursor cursor = mContentResolver.query(
819                builder.build(), mQuery.getProjection(), null, null, null);
820        final long end = System.currentTimeMillis();
821        if (DEBUG) {
822            Log.d(TAG, "Time for autocomplete (query: " + constraint
823                    + ", directoryId: " + directoryId + ", num_of_results: "
824                    + (cursor != null ? cursor.getCount() : "null") + "): "
825                    + (end - start) + " ms");
826        }
827        return cursor;
828    }
829
830    // TODO: This won't be used at all. We should find better way to quit the thread..
831    /*public void close() {
832        mEntries = null;
833        mPhotoCacheMap.evictAll();
834        if (!sPhotoHandlerThread.quit()) {
835            Log.w(TAG, "Failed to quit photo handler thread, ignoring it.");
836        }
837    }*/
838
839    @Override
840    public int getCount() {
841        final List<RecipientEntry> entries = getEntries();
842        return entries != null ? entries.size() : 0;
843    }
844
845    @Override
846    public Object getItem(int position) {
847        return getEntries().get(position);
848    }
849
850    @Override
851    public long getItemId(int position) {
852        return position;
853    }
854
855    @Override
856    public int getViewTypeCount() {
857        return RecipientEntry.ENTRY_TYPE_SIZE;
858    }
859
860    @Override
861    public int getItemViewType(int position) {
862        return getEntries().get(position).getEntryType();
863    }
864
865    @Override
866    public boolean isEnabled(int position) {
867        return getEntries().get(position).isSelectable();
868    }
869
870    @Override
871    public View getView(int position, View convertView, ViewGroup parent) {
872        final RecipientEntry entry = getEntries().get(position);
873        String displayName = entry.getDisplayName();
874        String destination = entry.getDestination();
875        if (TextUtils.isEmpty(displayName) || TextUtils.equals(displayName, destination)) {
876            displayName = destination;
877
878            // We only show the destination for secondary entries, so clear it
879            // only for the first level.
880            if (entry.isFirstLevel()) {
881                destination = null;
882            }
883        }
884
885        final View itemView = convertView != null ? convertView : mInflater.inflate(
886                getItemLayout(), parent, false);
887        final TextView displayNameView = (TextView) itemView.findViewById(getDisplayNameId());
888        final TextView destinationView = (TextView) itemView.findViewById(getDestinationId());
889        final TextView destinationTypeView = (TextView) itemView
890                .findViewById(getDestinationTypeId());
891        final ImageView imageView = (ImageView) itemView.findViewById(getPhotoId());
892        displayNameView.setText(displayName);
893        if (!TextUtils.isEmpty(destination)) {
894            destinationView.setText(destination);
895        } else {
896            destinationView.setText(null);
897        }
898        if (destinationTypeView != null) {
899            final CharSequence destinationType = mQuery
900                    .getTypeLabel(mContext.getResources(), entry.getDestinationType(),
901                            entry.getDestinationLabel()).toString().toUpperCase();
902
903            destinationTypeView.setText(destinationType);
904        }
905
906        if (entry.isFirstLevel()) {
907            displayNameView.setVisibility(View.VISIBLE);
908            if (imageView != null) {
909                imageView.setVisibility(View.VISIBLE);
910                final byte[] photoBytes = entry.getPhotoBytes();
911                if (photoBytes != null) {
912                    final Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0,
913                            photoBytes.length);
914                    imageView.setImageBitmap(photo);
915                } else {
916                    imageView.setImageResource(getDefaultPhotoResource());
917                }
918            }
919        } else {
920            displayNameView.setVisibility(View.GONE);
921            if (imageView != null) {
922                imageView.setVisibility(View.INVISIBLE);
923            }
924        }
925        return itemView;
926    }
927
928    /**
929     * Returns a layout id for each item inside auto-complete list.
930     *
931     * Each View must contain two TextViews (for display name and destination) and one ImageView
932     * (for photo). Ids for those should be available via {@link #getDisplayNameId()},
933     * {@link #getDestinationId()}, and {@link #getPhotoId()}.
934     */
935    protected int getItemLayout() {
936        return R.layout.chips_recipient_dropdown_item;
937    }
938
939    /**
940     * Returns a resource ID representing an image which should be shown when ther's no relevant
941     * photo is available.
942     */
943    protected int getDefaultPhotoResource() {
944        return R.drawable.ic_contact_picture;
945    }
946
947    /**
948     * Returns an id for TextView in an item View for showing a display name. By default
949     * {@link android.R.id#title} is returned.
950     */
951    protected int getDisplayNameId() {
952        return android.R.id.title;
953    }
954
955    /**
956     * Returns an id for TextView in an item View for showing a destination
957     * (an email address or a phone number).
958     * By default {@link android.R.id#text1} is returned.
959     */
960    protected int getDestinationId() {
961        return android.R.id.text1;
962    }
963
964    /**
965     * Returns an id for TextView in an item View for showing the type of the destination.
966     * By default {@link android.R.id#text2} is returned.
967     */
968    protected int getDestinationTypeId() {
969        return android.R.id.text2;
970    }
971
972    /**
973     * Returns an id for ImageView in an item View for showing photo image for a person. In default
974     * {@link android.R.id#icon} is returned.
975     */
976    protected int getPhotoId() {
977        return android.R.id.icon;
978    }
979
980    public Account getAccount() {
981        return mAccount;
982    }
983}
984