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