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    private static final int ALLOWANCE_FOR_DUPLICATES = 5;
77
78    // This is ContactsContract.PRIMARY_ACCOUNT_NAME. Available from ICS as hidden
79    private static final String PRIMARY_ACCOUNT_NAME = "name_for_primary_account";
80    // This is ContactsContract.PRIMARY_ACCOUNT_TYPE. Available from ICS as hidden
81    private 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    private 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(false,
238                            entryMap, nonAggregatedEntries, existingDestinations);
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(directoryCursor);
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(false,
428                    mEntryMap, mNonAggregatedEntries, mExistingDestinations));
429        }
430    }
431
432    private final Context mContext;
433    private final ContentResolver mContentResolver;
434    private final LayoutInflater mInflater;
435    private Account mAccount;
436    private final int mPreferredMaxResultCount;
437    private final Handler mHandler = new Handler();
438
439    /**
440     * {@link #mEntries} is responsible for showing every result for this Adapter. To
441     * construct it, we use {@link #mEntryMap}, {@link #mNonAggregatedEntries}, and
442     * {@link #mExistingDestinations}.
443     *
444     * First, each destination (an email address or a phone number) with a valid contactId is
445     * inserted into {@link #mEntryMap} and grouped by the contactId. Destinations without valid
446     * contactId (possible if they aren't in local storage) are stored in
447     * {@link #mNonAggregatedEntries}.
448     * Duplicates are removed using {@link #mExistingDestinations}.
449     *
450     * After having all results from Cursor objects, all destinations in mEntryMap are copied to
451     * {@link #mEntries}. If the number of destinations is not enough (i.e. less than
452     * {@link #mPreferredMaxResultCount}), destinations in mNonAggregatedEntries are also used.
453     *
454     * These variables are only used in UI thread, thus should not be touched in
455     * performFiltering() methods.
456     */
457    private LinkedHashMap<Long, List<RecipientEntry>> mEntryMap;
458    private List<RecipientEntry> mNonAggregatedEntries;
459    private Set<String> mExistingDestinations;
460    /** Note: use {@link #updateEntries(List)} to update this variable. */
461    private List<RecipientEntry> mEntries;
462    private List<RecipientEntry> mTempEntries;
463
464    /** The number of directories this adapter is waiting for results. */
465    private int mRemainingDirectoryCount;
466
467    /**
468     * Used to ignore asynchronous queries with a different constraint, which may happen when
469     * users type characters quickly.
470     */
471    private CharSequence mCurrentConstraint;
472
473    private final LruCache<Uri, byte[]> mPhotoCacheMap;
474
475    /**
476     * Handler specific for maintaining "Waiting for more contacts" message, which will be shown
477     * when:
478     * - there are directories to be searched
479     * - results from directories are slow to come
480     */
481    private final class DelayedMessageHandler extends Handler {
482        @Override
483        public void handleMessage(Message msg) {
484            if (mRemainingDirectoryCount > 0) {
485                updateEntries(constructEntryList(true,
486                        mEntryMap, mNonAggregatedEntries, mExistingDestinations));
487            }
488        }
489
490        public void sendDelayedLoadMessage() {
491            sendMessageDelayed(obtainMessage(MESSAGE_SEARCH_PENDING, 0, 0, null),
492                    MESSAGE_SEARCH_PENDING_DELAY);
493        }
494
495        public void removeDelayedLoadMessage() {
496            removeMessages(MESSAGE_SEARCH_PENDING);
497        }
498    }
499
500    private final DelayedMessageHandler mDelayedMessageHandler = new DelayedMessageHandler();
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    private List<DirectorySearchParams> setupOtherDirectories(Cursor directoryCursor) {
558        final PackageManager packageManager = mContext.getPackageManager();
559        final List<DirectorySearchParams> paramsList = new ArrayList<DirectorySearchParams>();
560        DirectorySearchParams preferredDirectory = null;
561        while (directoryCursor.moveToNext()) {
562            final long id = directoryCursor.getLong(DirectoryListQuery.ID);
563
564            // Skip the local invisible directory, because the default directory already includes
565            // all local results.
566            if (id == Directory.LOCAL_INVISIBLE) {
567                continue;
568            }
569
570            final DirectorySearchParams params = new DirectorySearchParams();
571            final String packageName = directoryCursor.getString(DirectoryListQuery.PACKAGE_NAME);
572            final int resourceId = directoryCursor.getInt(DirectoryListQuery.TYPE_RESOURCE_ID);
573            params.directoryId = id;
574            params.displayName = directoryCursor.getString(DirectoryListQuery.DISPLAY_NAME);
575            params.accountName = directoryCursor.getString(DirectoryListQuery.ACCOUNT_NAME);
576            params.accountType = directoryCursor.getString(DirectoryListQuery.ACCOUNT_TYPE);
577            if (packageName != null && resourceId != 0) {
578                try {
579                    final Resources resources =
580                            packageManager.getResourcesForApplication(packageName);
581                    params.directoryType = resources.getString(resourceId);
582                    if (params.directoryType == null) {
583                        Log.e(TAG, "Cannot resolve directory name: "
584                                + resourceId + "@" + packageName);
585                    }
586                } catch (NameNotFoundException e) {
587                    Log.e(TAG, "Cannot resolve directory name: "
588                            + resourceId + "@" + packageName, e);
589                }
590            }
591
592            // If an account has been provided and we found a directory that
593            // corresponds to that account, place that directory second, directly
594            // underneath the local contacts.
595            if (mAccount != null && mAccount.name.equals(params.accountName) &&
596                    mAccount.type.equals(params.accountType)) {
597                preferredDirectory = params;
598            } else {
599                paramsList.add(params);
600            }
601        }
602
603        if (preferredDirectory != null) {
604            paramsList.add(1, preferredDirectory);
605        }
606
607        return paramsList;
608    }
609
610    /**
611     * Starts search in other directories using {@link Filter}. Results will be handled in
612     * {@link DirectoryFilter}.
613     */
614    private void startSearchOtherDirectories(
615            CharSequence constraint, List<DirectorySearchParams> paramsList, int limit) {
616        final int count = paramsList.size();
617        // Note: skipping the default partition (index 0), which has already been loaded
618        for (int i = 1; i < count; i++) {
619            final DirectorySearchParams params = paramsList.get(i);
620            params.constraint = constraint;
621            if (params.filter == null) {
622                params.filter = new DirectoryFilter(params);
623            }
624            params.filter.setLimit(limit);
625            params.filter.filter(constraint);
626        }
627
628        // Directory search started. We may show "waiting" message if directory results are slow
629        // enough.
630        mRemainingDirectoryCount = count - 1;
631        mDelayedMessageHandler.sendDelayedLoadMessage();
632    }
633
634    private void putOneEntry(TemporaryEntry entry, boolean isAggregatedEntry,
635            LinkedHashMap<Long, List<RecipientEntry>> entryMap,
636            List<RecipientEntry> nonAggregatedEntries,
637            Set<String> existingDestinations) {
638        if (existingDestinations.contains(entry.destination)) {
639            return;
640        }
641
642        existingDestinations.add(entry.destination);
643
644        if (!isAggregatedEntry) {
645            nonAggregatedEntries.add(RecipientEntry.constructTopLevelEntry(
646                    entry.displayName,
647                    entry.displayNameSource,
648                    entry.destination, entry.destinationType, entry.destinationLabel,
649                    entry.contactId, entry.dataId, entry.thumbnailUriString));
650        } else if (entryMap.containsKey(entry.contactId)) {
651            // We already have a section for the person.
652            final List<RecipientEntry> entryList = entryMap.get(entry.contactId);
653            entryList.add(RecipientEntry.constructSecondLevelEntry(
654                    entry.displayName,
655                    entry.displayNameSource,
656                    entry.destination, entry.destinationType, entry.destinationLabel,
657                    entry.contactId, entry.dataId, entry.thumbnailUriString));
658        } else {
659            final List<RecipientEntry> entryList = new ArrayList<RecipientEntry>();
660            entryList.add(RecipientEntry.constructTopLevelEntry(
661                    entry.displayName,
662                    entry.displayNameSource,
663                    entry.destination, entry.destinationType, entry.destinationLabel,
664                    entry.contactId, entry.dataId, entry.thumbnailUriString));
665            entryMap.put(entry.contactId, entryList);
666        }
667    }
668
669    /**
670     * Constructs an actual list for this Adapter using {@link #mEntryMap}. Also tries to
671     * fetch a cached photo for each contact entry (other than separators), or request another
672     * thread to get one from directories.
673     */
674    private List<RecipientEntry> constructEntryList(
675            boolean showMessageIfDirectoryLoadRemaining,
676            LinkedHashMap<Long, List<RecipientEntry>> entryMap,
677            List<RecipientEntry> nonAggregatedEntries,
678            Set<String> existingDestinations) {
679        final List<RecipientEntry> entries = new ArrayList<RecipientEntry>();
680        int validEntryCount = 0;
681        for (Map.Entry<Long, List<RecipientEntry>> mapEntry : entryMap.entrySet()) {
682            final List<RecipientEntry> entryList = mapEntry.getValue();
683            final int size = entryList.size();
684            for (int i = 0; i < size; i++) {
685                RecipientEntry entry = entryList.get(i);
686                entries.add(entry);
687                tryFetchPhoto(entry);
688                validEntryCount++;
689            }
690            if (validEntryCount > mPreferredMaxResultCount) {
691                break;
692            }
693        }
694        if (validEntryCount <= mPreferredMaxResultCount) {
695            for (RecipientEntry entry : nonAggregatedEntries) {
696                if (validEntryCount > mPreferredMaxResultCount) {
697                    break;
698                }
699                entries.add(entry);
700                tryFetchPhoto(entry);
701
702                validEntryCount++;
703            }
704        }
705
706        return entries;
707    }
708
709    /** Resets {@link #mEntries} and notify the event to its parent ListView. */
710    private void updateEntries(List<RecipientEntry> newEntries) {
711        mEntries = newEntries;
712        notifyDataSetChanged();
713    }
714
715    private void cacheCurrentEntries() {
716        mTempEntries = mEntries;
717    }
718
719    private void clearTempEntries() {
720        mTempEntries = null;
721    }
722
723    private List<RecipientEntry> getEntries() {
724        return mTempEntries != null ? mTempEntries : mEntries;
725    }
726
727    private void tryFetchPhoto(final RecipientEntry entry) {
728        final Uri photoThumbnailUri = entry.getPhotoThumbnailUri();
729        if (photoThumbnailUri != null) {
730            final byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
731            if (photoBytes != null) {
732                entry.setPhotoBytes(photoBytes);
733                // notifyDataSetChanged() should be called by a caller.
734            } else {
735                if (DEBUG) {
736                    Log.d(TAG, "No photo cache for " + entry.getDisplayName()
737                            + ". Fetch one asynchronously");
738                }
739                fetchPhotoAsync(entry, photoThumbnailUri);
740            }
741        }
742    }
743
744    private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
745        final AsyncTask<Void, Void, Void> photoLoadTask = new AsyncTask<Void, Void, Void>() {
746            @Override
747            protected Void doInBackground(Void... params) {
748                final Cursor photoCursor = mContentResolver.query(
749                        photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null);
750                if (photoCursor != null) {
751                    try {
752                        if (photoCursor.moveToFirst()) {
753                            final byte[] photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
754                            entry.setPhotoBytes(photoBytes);
755
756                            mHandler.post(new Runnable() {
757                                @Override
758                                public void run() {
759                                    mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
760                                    notifyDataSetChanged();
761                                }
762                            });
763                        }
764                    } finally {
765                        photoCursor.close();
766                    }
767                }
768                return null;
769            }
770        };
771        photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
772    }
773
774    protected void fetchPhoto(final RecipientEntry entry, final Uri photoThumbnailUri) {
775        byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
776        if (photoBytes != null) {
777            entry.setPhotoBytes(photoBytes);
778            return;
779        }
780        final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION,
781                null, null, null);
782        if (photoCursor != null) {
783            try {
784                if (photoCursor.moveToFirst()) {
785                    photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
786                    entry.setPhotoBytes(photoBytes);
787                    mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
788                }
789            } finally {
790                photoCursor.close();
791            }
792        }
793    }
794
795    private Cursor doQuery(CharSequence constraint, int limit, Long directoryId) {
796        final Uri.Builder builder = mQuery.getContentFilterUri().buildUpon()
797                .appendPath(constraint.toString())
798                .appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY,
799                        String.valueOf(limit + ALLOWANCE_FOR_DUPLICATES));
800        if (directoryId != null) {
801            builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
802                    String.valueOf(directoryId));
803        }
804        if (mAccount != null) {
805            builder.appendQueryParameter(PRIMARY_ACCOUNT_NAME, mAccount.name);
806            builder.appendQueryParameter(PRIMARY_ACCOUNT_TYPE, mAccount.type);
807        }
808        final long start = System.currentTimeMillis();
809        final Cursor cursor = mContentResolver.query(
810                builder.build(), mQuery.getProjection(), null, null, null);
811        final long end = System.currentTimeMillis();
812        if (DEBUG) {
813            Log.d(TAG, "Time for autocomplete (query: " + constraint
814                    + ", directoryId: " + directoryId + ", num_of_results: "
815                    + (cursor != null ? cursor.getCount() : "null") + "): "
816                    + (end - start) + " ms");
817        }
818        return cursor;
819    }
820
821    // TODO: This won't be used at all. We should find better way to quit the thread..
822    /*public void close() {
823        mEntries = null;
824        mPhotoCacheMap.evictAll();
825        if (!sPhotoHandlerThread.quit()) {
826            Log.w(TAG, "Failed to quit photo handler thread, ignoring it.");
827        }
828    }*/
829
830    @Override
831    public int getCount() {
832        final List<RecipientEntry> entries = getEntries();
833        return entries != null ? entries.size() : 0;
834    }
835
836    @Override
837    public Object getItem(int position) {
838        return getEntries().get(position);
839    }
840
841    @Override
842    public long getItemId(int position) {
843        return position;
844    }
845
846    @Override
847    public int getViewTypeCount() {
848        return RecipientEntry.ENTRY_TYPE_SIZE;
849    }
850
851    @Override
852    public int getItemViewType(int position) {
853        return getEntries().get(position).getEntryType();
854    }
855
856    @Override
857    public boolean isEnabled(int position) {
858        return getEntries().get(position).isSelectable();
859    }
860
861    @Override
862    public View getView(int position, View convertView, ViewGroup parent) {
863        final RecipientEntry entry = getEntries().get(position);
864        String displayName = entry.getDisplayName();
865        String destination = entry.getDestination();
866        if (TextUtils.isEmpty(displayName) || TextUtils.equals(displayName, destination)) {
867            displayName = destination;
868
869            // We only show the destination for secondary entries, so clear it
870            // only for the first level.
871            if (entry.isFirstLevel()) {
872                destination = null;
873            }
874        }
875
876        final View itemView = convertView != null ? convertView : mInflater.inflate(
877                getItemLayout(), parent, false);
878        final TextView displayNameView = (TextView) itemView.findViewById(getDisplayNameId());
879        final TextView destinationView = (TextView) itemView.findViewById(getDestinationId());
880        final TextView destinationTypeView = (TextView) itemView
881                .findViewById(getDestinationTypeId());
882        final ImageView imageView = (ImageView) itemView.findViewById(getPhotoId());
883        displayNameView.setText(displayName);
884        if (!TextUtils.isEmpty(destination)) {
885            destinationView.setText(destination);
886        } else {
887            destinationView.setText(null);
888        }
889        if (destinationTypeView != null) {
890            final CharSequence destinationType = mQuery
891                    .getTypeLabel(mContext.getResources(), entry.getDestinationType(),
892                            entry.getDestinationLabel()).toString().toUpperCase();
893
894            destinationTypeView.setText(destinationType);
895        }
896
897        if (entry.isFirstLevel()) {
898            displayNameView.setVisibility(View.VISIBLE);
899            if (imageView != null) {
900                imageView.setVisibility(View.VISIBLE);
901                final byte[] photoBytes = entry.getPhotoBytes();
902                if (photoBytes != null && imageView != null) {
903                    final Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0,
904                            photoBytes.length);
905                    imageView.setImageBitmap(photo);
906                } else {
907                    imageView.setImageResource(getDefaultPhotoResource());
908                }
909            }
910        } else {
911            displayNameView.setVisibility(View.GONE);
912            if (imageView != null) {
913                imageView.setVisibility(View.INVISIBLE);
914            }
915        }
916        return itemView;
917    }
918
919    /**
920     * Returns a layout id for each item inside auto-complete list.
921     *
922     * Each View must contain two TextViews (for display name and destination) and one ImageView
923     * (for photo). Ids for those should be available via {@link #getDisplayNameId()},
924     * {@link #getDestinationId()}, and {@link #getPhotoId()}.
925     */
926    protected int getItemLayout() {
927        return R.layout.chips_recipient_dropdown_item;
928    }
929
930    /**
931     * Returns a resource ID representing an image which should be shown when ther's no relevant
932     * photo is available.
933     */
934    protected int getDefaultPhotoResource() {
935        return R.drawable.ic_contact_picture;
936    }
937
938    /**
939     * Returns an id for TextView in an item View for showing a display name. By default
940     * {@link android.R.id#title} is returned.
941     */
942    protected int getDisplayNameId() {
943        return android.R.id.title;
944    }
945
946    /**
947     * Returns an id for TextView in an item View for showing a destination
948     * (an email address or a phone number).
949     * By default {@link android.R.id#text1} is returned.
950     */
951    protected int getDestinationId() {
952        return android.R.id.text1;
953    }
954
955    /**
956     * Returns an id for TextView in an item View for showing the type of the destination.
957     * By default {@link android.R.id#text2} is returned.
958     */
959    protected int getDestinationTypeId() {
960        return android.R.id.text2;
961    }
962
963    /**
964     * Returns an id for ImageView in an item View for showing photo image for a person. In default
965     * {@link android.R.id#icon} is returned.
966     */
967    protected int getPhotoId() {
968        return android.R.id.icon;
969    }
970}
971