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