QuickContactActivity.java revision 9f2a5e78c9604d9c407f1464c7cb72ec5f2bb04d
1/*
2 * Copyright (C) 2009 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.contacts.quickcontact;
18
19import android.app.Activity;
20import android.app.Fragment;
21import android.app.FragmentManager;
22import android.app.LoaderManager.LoaderCallbacks;
23import android.content.ActivityNotFoundException;
24import android.content.ContentUris;
25import android.content.Context;
26import android.content.Intent;
27import android.content.Loader;
28import android.content.pm.PackageManager;
29import android.graphics.Rect;
30import android.graphics.drawable.Drawable;
31import android.net.Uri;
32import android.os.Bundle;
33import android.os.Handler;
34import android.provider.ContactsContract.CommonDataKinds.Email;
35import android.provider.ContactsContract.CommonDataKinds.Phone;
36import android.provider.ContactsContract.CommonDataKinds.SipAddress;
37import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
38import android.provider.ContactsContract.CommonDataKinds.Website;
39import android.provider.ContactsContract.Contacts;
40import android.provider.ContactsContract.QuickContact;
41import android.provider.ContactsContract.RawContacts;
42import android.support.v13.app.FragmentPagerAdapter;
43import android.support.v4.view.ViewPager;
44import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
45import android.text.TextUtils;
46import android.util.Log;
47import android.view.MotionEvent;
48import android.view.View;
49import android.view.View.OnClickListener;
50import android.view.ViewGroup;
51import android.view.WindowManager;
52import android.widget.HorizontalScrollView;
53import android.widget.ImageButton;
54import android.widget.ImageView;
55import android.widget.RelativeLayout;
56import android.widget.TextView;
57import android.widget.Toast;
58
59import com.android.contacts.common.Collapser;
60import com.android.contacts.R;
61import com.android.contacts.model.AccountTypeManager;
62import com.android.contacts.model.Contact;
63import com.android.contacts.model.ContactLoader;
64import com.android.contacts.model.RawContact;
65import com.android.contacts.model.account.AccountType;
66import com.android.contacts.model.dataitem.DataItem;
67import com.android.contacts.model.dataitem.DataKind;
68import com.android.contacts.model.dataitem.EmailDataItem;
69import com.android.contacts.model.dataitem.ImDataItem;
70import com.android.contacts.util.Constants;
71import com.android.contacts.util.DataStatus;
72import com.android.contacts.util.ImageViewDrawableSetter;
73import com.android.contacts.util.SchedulingUtils;
74import com.android.contacts.common.util.StopWatch;
75import com.google.common.base.Preconditions;
76import com.google.common.collect.Lists;
77
78import java.util.HashMap;
79import java.util.HashSet;
80import java.util.List;
81import java.util.Set;
82
83// TODO: Save selected tab index during rotation
84
85/**
86 * Mostly translucent {@link Activity} that shows QuickContact dialog. It loads
87 * data asynchronously, and then shows a popup with details centered around
88 * {@link Intent#getSourceBounds()}.
89 */
90public class QuickContactActivity extends Activity {
91    private static final String TAG = "QuickContact";
92
93    private static final boolean TRACE_LAUNCH = false;
94    private static final String TRACE_TAG = "quickcontact";
95    private static final int POST_DRAW_WAIT_DURATION = 60;
96    private static final boolean ENABLE_STOPWATCH = false;
97
98
99    @SuppressWarnings("deprecation")
100    private static final String LEGACY_AUTHORITY = android.provider.Contacts.AUTHORITY;
101
102    private Uri mLookupUri;
103    private String[] mExcludeMimes;
104    private List<String> mSortedActionMimeTypes = Lists.newArrayList();
105
106    private FloatingChildLayout mFloatingLayout;
107
108    private View mPhotoContainer;
109    private ViewGroup mTrack;
110    private HorizontalScrollView mTrackScroller;
111    private View mSelectedTabRectangle;
112    private View mLineAfterTrack;
113
114    private ImageButton mOpenDetailsButton;
115    private ImageButton mOpenDetailsPushLayerButton;
116    private ViewPager mListPager;
117
118    private ContactLoader mContactLoader;
119
120    private final ImageViewDrawableSetter mPhotoSetter = new ImageViewDrawableSetter();
121
122    /**
123     * Keeps the default action per mimetype. Empty if no default actions are set
124     */
125    private HashMap<String, Action> mDefaultsMap = new HashMap<String, Action>();
126
127    /**
128     * Set of {@link Action} that are associated with the aggregate currently
129     * displayed by this dialog, represented as a map from {@link String}
130     * MIME-type to a list of {@link Action}.
131     */
132    private ActionMultiMap mActions = new ActionMultiMap();
133
134    /**
135     * {@link #LEADING_MIMETYPES} and {@link #TRAILING_MIMETYPES} are used to sort MIME-types.
136     *
137     * <p>The MIME-types in {@link #LEADING_MIMETYPES} appear in the front of the dialog,
138     * in the order specified here.</p>
139     *
140     * <p>The ones in {@link #TRAILING_MIMETYPES} appear in the end of the dialog, in the order
141     * specified here.</p>
142     *
143     * <p>The rest go between them, in the order in the array.</p>
144     */
145    private static final List<String> LEADING_MIMETYPES = Lists.newArrayList(
146            Phone.CONTENT_ITEM_TYPE, SipAddress.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE);
147
148    /** See {@link #LEADING_MIMETYPES}. */
149    private static final List<String> TRAILING_MIMETYPES = Lists.newArrayList(
150            StructuredPostal.CONTENT_ITEM_TYPE, Website.CONTENT_ITEM_TYPE);
151
152    /** Id for the background loader */
153    private static final int LOADER_ID = 0;
154
155    private StopWatch mStopWatch = ENABLE_STOPWATCH
156            ? StopWatch.start("QuickContact") : StopWatch.getNullStopWatch();
157
158    @Override
159    protected void onCreate(Bundle icicle) {
160        mStopWatch.lap("c"); // create start
161        super.onCreate(icicle);
162
163        mStopWatch.lap("sc"); // super.onCreate
164
165        if (TRACE_LAUNCH) android.os.Debug.startMethodTracing(TRACE_TAG);
166
167        // Parse intent
168        final Intent intent = getIntent();
169
170        Uri lookupUri = intent.getData();
171
172        // Check to see whether it comes from the old version.
173        if (lookupUri != null && LEGACY_AUTHORITY.equals(lookupUri.getAuthority())) {
174            final long rawContactId = ContentUris.parseId(lookupUri);
175            lookupUri = RawContacts.getContactLookupUri(getContentResolver(),
176                    ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
177        }
178
179        mLookupUri = Preconditions.checkNotNull(lookupUri, "missing lookupUri");
180
181        mExcludeMimes = intent.getStringArrayExtra(QuickContact.EXTRA_EXCLUDE_MIMES);
182
183        mStopWatch.lap("i"); // intent parsed
184
185        mContactLoader = (ContactLoader) getLoaderManager().initLoader(
186                LOADER_ID, null, mLoaderCallbacks);
187
188        mStopWatch.lap("ld"); // loader started
189
190        // Show QuickContact in front of soft input
191        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
192                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
193
194        setContentView(R.layout.quickcontact_activity);
195
196        mStopWatch.lap("l"); // layout inflated
197
198        mFloatingLayout = (FloatingChildLayout) findViewById(R.id.floating_layout);
199        mTrack = (ViewGroup) findViewById(R.id.track);
200        mTrackScroller = (HorizontalScrollView) findViewById(R.id.track_scroller);
201        mOpenDetailsButton = (ImageButton) findViewById(R.id.open_details_button);
202        mOpenDetailsPushLayerButton = (ImageButton) findViewById(R.id.open_details_push_layer);
203        mListPager = (ViewPager) findViewById(R.id.item_list_pager);
204        mSelectedTabRectangle = findViewById(R.id.selected_tab_rectangle);
205        mLineAfterTrack = findViewById(R.id.line_after_track);
206
207        mFloatingLayout.setOnOutsideTouchListener(new View.OnTouchListener() {
208            @Override
209            public boolean onTouch(View v, MotionEvent event) {
210                handleOutsideTouch();
211                return true;
212            }
213        });
214
215        final OnClickListener openDetailsClickHandler = new OnClickListener() {
216            @Override
217            public void onClick(View v) {
218                final Intent intent = new Intent(Intent.ACTION_VIEW, mLookupUri);
219                mContactLoader.cacheResult();
220                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
221                startActivity(intent);
222                close(false);
223            }
224        };
225        mOpenDetailsButton.setOnClickListener(openDetailsClickHandler);
226        mOpenDetailsPushLayerButton.setOnClickListener(openDetailsClickHandler);
227        mListPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
228        mListPager.setOnPageChangeListener(new PageChangeListener());
229
230        final Rect sourceBounds = intent.getSourceBounds();
231        if (sourceBounds != null) {
232            mFloatingLayout.setChildTargetScreen(sourceBounds);
233        }
234
235        // find and prepare correct header view
236        mPhotoContainer = findViewById(R.id.photo_container);
237        setHeaderNameText(R.id.name, R.string.missing_name);
238
239        mStopWatch.lap("v"); // view initialized
240
241        SchedulingUtils.doAfterLayout(mFloatingLayout, new Runnable() {
242            @Override
243            public void run() {
244                mFloatingLayout.fadeInBackground();
245            }
246        });
247
248        mStopWatch.lap("cf"); // onCreate finished
249    }
250
251    private void handleOutsideTouch() {
252        if (mFloatingLayout.isContentFullyVisible()) {
253            close(true);
254        }
255    }
256
257    private void close(boolean withAnimation) {
258        // cancel any pending queries
259        getLoaderManager().destroyLoader(LOADER_ID);
260
261        if (withAnimation) {
262            mFloatingLayout.fadeOutBackground();
263            final boolean animated = mFloatingLayout.hideContent(new Runnable() {
264                @Override
265                public void run() {
266                    // Wait until the final animation frame has been drawn, otherwise
267                    // there is jank as the framework transitions to the next Activity.
268                    SchedulingUtils.doAfterDraw(mFloatingLayout, new Runnable() {
269                        @Override
270                        public void run() {
271                            // Unfortunately, we need to also use postDelayed() to wait a moment
272                            // for the frame to be drawn, else the framework's activity-transition
273                            // animation will kick in before the final frame is available to it.
274                            // This seems unavoidable.  The problem isn't merely that there is no
275                            // post-draw listener API; if that were so, it would be sufficient to
276                            // call post() instead of postDelayed().
277                            new Handler().postDelayed(new Runnable() {
278                                @Override
279                                public void run() {
280                                    finish();
281                                }
282                            }, POST_DRAW_WAIT_DURATION);
283                        }
284                    });
285                }
286            });
287            if (!animated) {
288                // If we were in the wrong state, simply quit (this can happen for example
289                // if the user pushes BACK before anything has loaded)
290                finish();
291            }
292        } else {
293            finish();
294        }
295    }
296
297    @Override
298    public void onBackPressed() {
299        close(true);
300    }
301
302    /** Assign this string to the view if it is not empty. */
303    private void setHeaderNameText(int id, int resId) {
304        setHeaderNameText(id, getText(resId));
305    }
306
307    /** Assign this string to the view if it is not empty. */
308    private void setHeaderNameText(int id, CharSequence value) {
309        final View view = mPhotoContainer.findViewById(id);
310        if (view instanceof TextView) {
311            if (!TextUtils.isEmpty(value)) {
312                ((TextView)view).setText(value);
313            }
314        }
315    }
316
317    /**
318     * Check if the given MIME-type appears in the list of excluded MIME-types
319     * that the most-recent caller requested.
320     */
321    private boolean isMimeExcluded(String mimeType) {
322        if (mExcludeMimes == null) return false;
323        for (String excludedMime : mExcludeMimes) {
324            if (TextUtils.equals(excludedMime, mimeType)) {
325                return true;
326            }
327        }
328        return false;
329    }
330
331    /**
332     * Handle the result from the ContactLoader
333     */
334    private void bindData(Contact data) {
335        final ResolveCache cache = ResolveCache.getInstance(this);
336        final Context context = this;
337
338        mOpenDetailsButton.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ? View.GONE
339                : View.VISIBLE);
340
341        mDefaultsMap.clear();
342
343        mStopWatch.lap("sph"); // Start photo setting
344
345        final ImageView photoView = (ImageView) mPhotoContainer.findViewById(R.id.photo);
346        mPhotoSetter.setupContactPhoto(data, photoView);
347
348        mStopWatch.lap("ph"); // Photo set
349
350        for (RawContact rawContact : data.getRawContacts()) {
351            for (DataItem dataItem : rawContact.getDataItems()) {
352                final String mimeType = dataItem.getMimeType();
353                final AccountType accountType = rawContact.getAccountType(this);
354                final DataKind dataKind = AccountTypeManager.getInstance(this)
355                        .getKindOrFallback(accountType, mimeType);
356
357                // Skip this data item if MIME-type excluded
358                if (isMimeExcluded(mimeType)) continue;
359
360                final long dataId = dataItem.getId();
361                final boolean isPrimary = dataItem.isPrimary();
362                final boolean isSuperPrimary = dataItem.isSuperPrimary();
363
364                if (dataKind != null) {
365                    // Build an action for this data entry, find a mapping to a UI
366                    // element, build its summary from the cursor, and collect it
367                    // along with all others of this MIME-type.
368                    final Action action = new DataAction(context, dataItem, dataKind);
369                    final boolean wasAdded = considerAdd(action, cache, isSuperPrimary);
370                    if (wasAdded) {
371                        // Remember the default
372                        if (isSuperPrimary || (isPrimary && (mDefaultsMap.get(mimeType) == null))) {
373                            mDefaultsMap.put(mimeType, action);
374                        }
375                    }
376                }
377
378                // Handle Email rows with presence data as Im entry
379                final DataStatus status = data.getStatuses().get(dataId);
380                if (status != null && dataItem instanceof EmailDataItem) {
381                    final EmailDataItem email = (EmailDataItem) dataItem;
382                    final ImDataItem im = ImDataItem.createFromEmail(email);
383                    if (dataKind != null) {
384                        final DataAction action = new DataAction(context, im, dataKind);
385                        action.setPresence(status.getPresence());
386                        considerAdd(action, cache, isSuperPrimary);
387                    }
388                }
389            }
390        }
391
392        mStopWatch.lap("e"); // Entities inflated
393
394        // Collapse Action Lists (remove e.g. duplicate e-mail addresses from different sources)
395        for (List<Action> actionChildren : mActions.values()) {
396            Collapser.collapseList(actionChildren);
397        }
398
399        mStopWatch.lap("c"); // List collapsed
400
401        setHeaderNameText(R.id.name, data.getDisplayName());
402
403        // All the mime-types to add.
404        final Set<String> containedTypes = new HashSet<String>(mActions.keySet());
405        mSortedActionMimeTypes.clear();
406        // First, add LEADING_MIMETYPES, which are most common.
407        for (String mimeType : LEADING_MIMETYPES) {
408            if (containedTypes.contains(mimeType)) {
409                mSortedActionMimeTypes.add(mimeType);
410                containedTypes.remove(mimeType);
411            }
412        }
413
414        // Add all the remaining ones that are not TRAILING
415        for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) {
416            if (!TRAILING_MIMETYPES.contains(mimeType)) {
417                mSortedActionMimeTypes.add(mimeType);
418                containedTypes.remove(mimeType);
419            }
420        }
421
422        // Then, add TRAILING_MIMETYPES, which are least common.
423        for (String mimeType : TRAILING_MIMETYPES) {
424            if (containedTypes.contains(mimeType)) {
425                containedTypes.remove(mimeType);
426                mSortedActionMimeTypes.add(mimeType);
427            }
428        }
429
430        mStopWatch.lap("mt"); // Mime types initialized
431
432        // Add buttons for each mimetype
433        mTrack.removeAllViews();
434        for (String mimeType : mSortedActionMimeTypes) {
435            final View actionView = inflateAction(mimeType, cache, mTrack);
436            mTrack.addView(actionView);
437        }
438
439        mStopWatch.lap("mt"); // Buttons added
440
441        final boolean hasData = !mSortedActionMimeTypes.isEmpty();
442        mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE);
443        mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE);
444        mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE);
445        mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE);
446    }
447
448    /**
449     * Consider adding the given {@link Action}, which will only happen if
450     * {@link PackageManager} finds an application to handle
451     * {@link Action#getIntent()}.
452     * @param action the action to handle
453     * @param resolveCache cache of applications that can handle actions
454     * @param front indicates whether to add the action to the front of the list
455     * @return true if action has been added
456     */
457    private boolean considerAdd(Action action, ResolveCache resolveCache, boolean front) {
458        if (resolveCache.hasResolve(action)) {
459            mActions.put(action.getMimeType(), action, front);
460            return true;
461        }
462        return false;
463    }
464
465    /**
466     * Inflate the in-track view for the action of the given MIME-type, collapsing duplicate values.
467     * Will use the icon provided by the {@link DataKind}.
468     */
469    private View inflateAction(String mimeType, ResolveCache resolveCache, ViewGroup root) {
470        final CheckableImageView typeView = (CheckableImageView) getLayoutInflater().inflate(
471                R.layout.quickcontact_track_button, root, false);
472
473        List<Action> children = mActions.get(mimeType);
474        typeView.setTag(mimeType);
475        final Action firstInfo = children.get(0);
476
477        // Set icon and listen for clicks
478        final CharSequence descrip = resolveCache.getDescription(firstInfo);
479        final Drawable icon = resolveCache.getIcon(firstInfo);
480        typeView.setChecked(false);
481        typeView.setContentDescription(descrip);
482        typeView.setImageDrawable(icon);
483        typeView.setOnClickListener(mTypeViewClickListener);
484
485        return typeView;
486    }
487
488    private CheckableImageView getActionViewAt(int position) {
489        return (CheckableImageView) mTrack.getChildAt(position);
490    }
491
492    @Override
493    public void onAttachFragment(Fragment fragment) {
494        final QuickContactListFragment listFragment = (QuickContactListFragment) fragment;
495        listFragment.setListener(mListFragmentListener);
496    }
497
498    private LoaderCallbacks<Contact> mLoaderCallbacks =
499            new LoaderCallbacks<Contact>() {
500        @Override
501        public void onLoaderReset(Loader<Contact> loader) {
502        }
503
504        @Override
505        public void onLoadFinished(Loader<Contact> loader, Contact data) {
506            mStopWatch.lap("lf"); // onLoadFinished
507            if (isFinishing()) {
508                close(false);
509                return;
510            }
511            if (data.isError()) {
512                // This shouldn't ever happen, so throw an exception. The {@link ContactLoader}
513                // should log the actual exception.
514                throw new IllegalStateException("Failed to load contact", data.getException());
515            }
516            if (data.isNotFound()) {
517                Log.i(TAG, "No contact found: " + ((ContactLoader)loader).getLookupUri());
518                Toast.makeText(QuickContactActivity.this, R.string.invalidContactMessage,
519                        Toast.LENGTH_LONG).show();
520                close(false);
521                return;
522            }
523
524            bindData(data);
525
526            mStopWatch.lap("bd"); // bindData finished
527
528            if (TRACE_LAUNCH) android.os.Debug.stopMethodTracing();
529            if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
530                Log.d(Constants.PERFORMANCE_TAG, "QuickContact shown");
531            }
532
533            // Data bound and ready, pull curtain to show. Put this on the Handler to ensure
534            // that the layout passes are completed
535            SchedulingUtils.doAfterLayout(mFloatingLayout, new Runnable() {
536                @Override
537                public void run() {
538                    mFloatingLayout.showContent(new Runnable() {
539                        @Override
540                        public void run() {
541                            mContactLoader.upgradeToFullContact();
542                        }
543                    });
544                }
545            });
546            mStopWatch.stopAndLog(TAG, 0);
547            mStopWatch = StopWatch.getNullStopWatch(); // We're done with it.
548        }
549
550        @Override
551        public Loader<Contact> onCreateLoader(int id, Bundle args) {
552            if (mLookupUri == null) {
553                Log.wtf(TAG, "Lookup uri wasn't initialized. Loader was started too early");
554            }
555            return new ContactLoader(getApplicationContext(), mLookupUri, false);
556        }
557    };
558
559    /** A type (e.g. Call/Addresses was clicked) */
560    private final OnClickListener mTypeViewClickListener = new OnClickListener() {
561        @Override
562        public void onClick(View view) {
563            final CheckableImageView actionView = (CheckableImageView)view;
564            final String mimeType = (String) actionView.getTag();
565            int index = mSortedActionMimeTypes.indexOf(mimeType);
566            mListPager.setCurrentItem(index, true);
567        }
568    };
569
570    private class ViewPagerAdapter extends FragmentPagerAdapter {
571        public ViewPagerAdapter(FragmentManager fragmentManager) {
572            super(fragmentManager);
573        }
574
575        @Override
576        public Fragment getItem(int position) {
577            QuickContactListFragment fragment = new QuickContactListFragment();
578            final String mimeType = mSortedActionMimeTypes.get(position);
579            final List<Action> actions = mActions.get(mimeType);
580            fragment.setActions(actions);
581            return fragment;
582        }
583
584        @Override
585        public int getCount() {
586            return mSortedActionMimeTypes.size();
587        }
588    }
589
590    private class PageChangeListener extends SimpleOnPageChangeListener {
591        @Override
592        public void onPageSelected(int position) {
593            final CheckableImageView actionView = getActionViewAt(position);
594            mTrackScroller.requestChildRectangleOnScreen(actionView,
595                    new Rect(0, 0, actionView.getWidth(), actionView.getHeight()), false);
596        }
597
598        @Override
599        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
600            final RelativeLayout.LayoutParams layoutParams =
601                    (RelativeLayout.LayoutParams) mSelectedTabRectangle.getLayoutParams();
602            final int width = mSelectedTabRectangle.getWidth();
603            layoutParams.leftMargin = (int) ((position + positionOffset) * width);
604            mSelectedTabRectangle.setLayoutParams(layoutParams);
605        }
606    }
607
608    private final QuickContactListFragment.Listener mListFragmentListener =
609            new QuickContactListFragment.Listener() {
610        @Override
611        public void onOutsideClick() {
612            // If there is no background, we want to dismiss, because to the user it seems
613            // like he had touched outside. If the ViewPager is solid however, those taps
614            // must be ignored
615            final boolean isTransparent = mListPager.getBackground() == null;
616            if (isTransparent) handleOutsideTouch();
617        }
618
619        @Override
620        public void onItemClicked(final Action action, final boolean alternate) {
621            final Runnable startAppRunnable = new Runnable() {
622                @Override
623                public void run() {
624                    try {
625                        startActivity(alternate ? action.getAlternateIntent() : action.getIntent());
626                    } catch (ActivityNotFoundException e) {
627                        Toast.makeText(QuickContactActivity.this, R.string.quickcontact_missing_app,
628                                Toast.LENGTH_SHORT).show();
629                    }
630
631                    close(false);
632                }
633            };
634            // Defer the action to make the window properly repaint
635            new Handler().post(startAppRunnable);
636        }
637    };
638}
639