MessageViewFragmentBase.java revision 91a1cf1db0b2a6ee72e467c37e7845584354eaf2
1/*
2 * Copyright (C) 2010 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.email.activity;
18
19import com.android.email.Controller;
20import com.android.email.ControllerResultUiThreadWrapper;
21import com.android.email.Email;
22import com.android.email.Preferences;
23import com.android.email.R;
24import com.android.email.Throttle;
25import com.android.email.Utility;
26import com.android.email.mail.Address;
27import com.android.email.mail.MessagingException;
28import com.android.email.mail.internet.EmailHtmlUtil;
29import com.android.email.mail.internet.MimeUtility;
30import com.android.email.provider.AttachmentProvider;
31import com.android.email.provider.EmailContent.Attachment;
32import com.android.email.provider.EmailContent.Body;
33import com.android.email.provider.EmailContent.Mailbox;
34import com.android.email.provider.EmailContent.Message;
35import com.android.email.service.AttachmentDownloadService;
36
37import org.apache.commons.io.IOUtils;
38
39import android.app.Activity;
40import android.app.Fragment;
41import android.app.LoaderManager.LoaderCallbacks;
42import android.content.ActivityNotFoundException;
43import android.content.ContentResolver;
44import android.content.ContentUris;
45import android.content.Context;
46import android.content.Intent;
47import android.content.Loader;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.res.Resources;
51import android.database.ContentObserver;
52import android.graphics.Bitmap;
53import android.graphics.BitmapFactory;
54import android.net.ConnectivityManager;
55import android.net.NetworkInfo;
56import android.net.Uri;
57import android.os.AsyncTask;
58import android.os.Bundle;
59import android.os.Environment;
60import android.os.Handler;
61import android.provider.ContactsContract;
62import android.provider.ContactsContract.QuickContact;
63import android.provider.Settings;
64import android.text.SpannableStringBuilder;
65import android.text.TextUtils;
66import android.text.format.DateUtils;
67import android.util.Log;
68import android.util.Patterns;
69import android.view.LayoutInflater;
70import android.view.View;
71import android.view.ViewGroup;
72import android.webkit.WebSettings;
73import android.webkit.WebView;
74import android.webkit.WebViewClient;
75import android.widget.Button;
76import android.widget.ImageView;
77import android.widget.LinearLayout;
78import android.widget.ProgressBar;
79import android.widget.TextView;
80
81import java.io.File;
82import java.io.FileOutputStream;
83import java.io.IOException;
84import java.io.InputStream;
85import java.io.OutputStream;
86import java.util.Formatter;
87import java.util.List;
88import java.util.regex.Matcher;
89import java.util.regex.Pattern;
90
91// TODO Better handling of config changes.
92// - Restore "Show pictures" state, scroll position and current tab
93// - Retain the content; don't kick 3 async tasks every time
94
95/**
96 * Base class for {@link MessageViewFragment} and {@link MessageFileViewFragment}.
97 *
98 * See {@link MessageViewBase} for the class relation diagram.
99 */
100public abstract class MessageViewFragmentBase extends Fragment implements View.OnClickListener {
101    private static final int PHOTO_LOADER_ID = 1;
102    private Context mContext;
103
104    // Regex that matches start of img tag. '<(?i)img\s+'.
105    private static final Pattern IMG_TAG_START_REGEX = Pattern.compile("<(?i)img\\s+");
106    // Regex that matches Web URL protocol part as case insensitive.
107    private static final Pattern WEB_URL_PROTOCOL = Pattern.compile("(?i)http|https://");
108
109    private static int PREVIEW_ICON_WIDTH = 62;
110    private static int PREVIEW_ICON_HEIGHT = 62;
111
112    private TextView mSubjectView;
113    private TextView mFromNameView;
114    private TextView mFromAddressView;
115    private TextView mDateTimeView;
116    private TextView mAddressesView;
117    private WebView mMessageContentView;
118    private LinearLayout mAttachments;
119    private View mTabSection;
120    private ImageView mFromBadge;
121    private ImageView mSenderPresenceView;
122    private View mMainView;
123    private View mLoadingProgress;
124    private Button mShowDetailsButton;
125
126    private TextView mMessageTab;
127    private TextView mAttachmentTab;
128    private TextView mInviteTab;
129    // It is not really a tab, but looks like one of them.
130    private TextView mShowPicturesTab;
131
132    private View mAttachmentsScroll;
133    private View mInviteScroll;
134
135    private long mAccountId = -1;
136    private long mMessageId = -1;
137    private Message mMessage;
138
139    private LoadMessageTask mLoadMessageTask;
140    private ReloadMessageTask mReloadMessageTask;
141    private LoadBodyTask mLoadBodyTask;
142    private LoadAttachmentsTask mLoadAttachmentsTask;
143
144    private Controller mController;
145    private ControllerResultUiThreadWrapper<ControllerResults> mControllerCallback;
146
147    // contains the HTML body. Is used by LoadAttachmentTask to display inline images.
148    // is null most of the time, is used transiently to pass info to LoadAttachementTask
149    private String mHtmlTextRaw;
150
151    // contains the HTML content as set in WebView.
152    private String mHtmlTextWebView;
153
154    private boolean mResumed;
155    private boolean mLoadWhenResumed;
156
157    private boolean mIsMessageLoadedForTest;
158
159    private MessageObserver mMessageObserver;
160
161    private static final int CONTACT_STATUS_STATE_UNLOADED = 0;
162    private static final int CONTACT_STATUS_STATE_UNLOADED_TRIGGERED = 1;
163    private static final int CONTACT_STATUS_STATE_LOADED = 2;
164
165    private int mContactStatusState;
166    private Uri mQuickContactLookupUri;
167
168    /** Flag for {@link #mTabFlags}: Message has attachment(s) */
169    protected static final int TAB_FLAGS_HAS_ATTACHMENT = 1;
170
171    /**
172     * Flag for {@link #mTabFlags}: Message contains invite.  This flag is only set by
173     * {@link MessageViewFragment}.
174     */
175    protected static final int TAB_FLAGS_HAS_INVITE = 2;
176
177    /** Flag for {@link #mTabFlags}: Message contains pictures */
178    protected static final int TAB_FLAGS_HAS_PICTURES = 4;
179
180    /** Flag for {@link #mTabFlags}: "Show pictures" has already been pressed */
181    protected static final int TAB_FLAGS_PICTURE_LOADED = 8;
182
183    /**
184     * Flags to control the tabs.
185     * @see #updateTabFlags(int)
186     */
187    private int mTabFlags;
188
189    /** # of attachments in the current message */
190    private int mAttachmentCount;
191
192    // Use (random) large values, to avoid confusion with TAB_FLAGS_*
193    protected static final int TAB_MESSAGE = 101;
194    protected static final int TAB_INVITE = 102;
195    protected static final int TAB_ATTACHMENT = 103;
196
197    /**
198     * Currently visible tab.  Any of {@link #TAB_MESSAGE}, {@link #TAB_INVITE} or
199     * {@link #TAB_ATTACHMENT}.
200     *
201     * Note we don't retain this value through configuration changes, as restoring the current tab
202     * would be clumsy with the current implementation where we load Message/Body/Attachments
203     * separately.  (e.g. # of attachments can't be obtained quickly enough to update the UI
204     * after screen rotation.)
205     */
206    private int mCurrentTab;
207
208    /**
209     * Zoom scales for webview.  Values correspond to {@link Preferences#TEXT_ZOOM_TINY}..
210     * {@link Preferences#TEXT_ZOOM_HUGE}.
211     */
212    private static final float[] ZOOM_SCALE_ARRAY = new float[] {0.8f, 0.9f, 1.0f, 1.2f, 1.5f};
213
214    /**
215     * Encapsulates known information about a single attachment.
216     *
217     * TODO: This should have methods to encapsulate the entire state graph of loading, canceling,
218     * viewing, and saving.
219     */
220    private static class AttachmentInfo {
221        public String name;
222        public String contentType;
223        public long size;
224        public long attachmentId;
225        public Button viewButton;
226        public Button saveButton;
227        public Button loadButton;
228        public Button cancelButton;
229        public ImageView iconView;
230        public ProgressBar progressView;
231        public boolean allowView;
232        public boolean allowSave;
233        public boolean isLoaded;
234    }
235
236    public interface Callback {
237        /** Called when the fragment is about to show up, or show a different message. */
238        public void onMessageViewShown(int mailboxType);
239
240        /** Called when the fragment is about to be destroyed. */
241        public void onMessageViewGone();
242
243        /**
244         * Called when a link in a message is clicked.
245         *
246         * @param url link url that's clicked.
247         * @return true if handled, false otherwise.
248         */
249        public boolean onUrlInMessageClicked(String url);
250
251        /**
252         * Called when the message specified doesn't exist, or is deleted/moved.
253         */
254        public void onMessageNotExists();
255
256        /** Called when it starts loading a message. */
257        public void onLoadMessageStarted();
258
259        /** Called when it successfully finishes loading a message. */
260        public void onLoadMessageFinished();
261
262        /** Called when an error occurred during loading a message. */
263        public void onLoadMessageError(String errorMessage);
264    }
265
266    public static class EmptyCallback implements Callback {
267        public static final Callback INSTANCE = new EmptyCallback();
268        @Override public void onMessageViewShown(int mailboxType) {}
269        @Override public void onMessageViewGone() {}
270        @Override public void onLoadMessageError(String errorMessage) {}
271        @Override public void onLoadMessageFinished() {}
272        @Override public void onLoadMessageStarted() {}
273        @Override public void onMessageNotExists() {}
274        @Override
275        public boolean onUrlInMessageClicked(String url) {
276            return false;
277        }
278    }
279
280    private Callback mCallback = EmptyCallback.INSTANCE;
281
282    @Override
283    public void onCreate(Bundle savedInstanceState) {
284        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
285            Log.d(Email.LOG_TAG, "MessageViewFragment onCreate");
286        }
287        super.onCreate(savedInstanceState);
288
289        mContext = getActivity().getApplicationContext();
290
291        mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
292                new Handler(), new ControllerResults());
293
294        mController = Controller.getInstance(mContext);
295        mMessageObserver = new MessageObserver(new Handler(), mContext);
296    }
297
298    @Override
299    public View onCreateView(
300            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
301        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
302            Log.d(Email.LOG_TAG, "MessageViewFragment onCreateView");
303        }
304        final View view = inflater.inflate(R.layout.message_view_fragment, container, false);
305
306        mSubjectView = (TextView) view.findViewById(R.id.subject);
307        mFromNameView = (TextView) view.findViewById(R.id.from_name);
308        mFromAddressView = (TextView) view.findViewById(R.id.from_address);
309        mAddressesView = (TextView) view.findViewById(R.id.addresses);
310        mDateTimeView = (TextView) view.findViewById(R.id.datetime);
311        mMessageContentView = (WebView) view.findViewById(R.id.message_content);
312        mAttachments = (LinearLayout) view.findViewById(R.id.attachments);
313        mTabSection = view.findViewById(R.id.message_tabs_section);
314        mFromBadge = (ImageView) view.findViewById(R.id.badge);
315        mSenderPresenceView = (ImageView) view.findViewById(R.id.presence);
316        mMainView = view.findViewById(R.id.main_panel);
317        mLoadingProgress = view.findViewById(R.id.loading_progress);
318        mShowDetailsButton = (Button) view.findViewById(R.id.show_details);
319
320        mFromNameView.setOnClickListener(this);
321        mFromAddressView.setOnClickListener(this);
322        mFromBadge.setOnClickListener(this);
323        mSenderPresenceView.setOnClickListener(this);
324
325        mMessageTab = (TextView) view.findViewById(R.id.show_message);
326        mAttachmentTab = (TextView) view.findViewById(R.id.show_attachments);
327        mShowPicturesTab = (TextView) view.findViewById(R.id.show_pictures);
328        // Invite is only used in MessageViewFragment, but visibility is controlled here.
329        mInviteTab = (TextView) view.findViewById(R.id.show_invite);
330
331        mMessageTab.setOnClickListener(this);
332        mAttachmentTab.setOnClickListener(this);
333        mShowPicturesTab.setOnClickListener(this);
334        mInviteTab.setOnClickListener(this);
335        mShowDetailsButton.setOnClickListener(this);
336
337        mAttachmentsScroll = view.findViewById(R.id.attachments_scroll);
338        mInviteScroll = view.findViewById(R.id.invite_scroll);
339
340        WebSettings webSettings = mMessageContentView.getSettings();
341        webSettings.setBlockNetworkLoads(true);
342        webSettings.setSupportZoom(true);
343        webSettings.setBuiltInZoomControls(true);
344        mMessageContentView.setWebViewClient(new CustomWebViewClient());
345        return view;
346    }
347
348    @Override
349    public void onActivityCreated(Bundle savedInstanceState) {
350        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
351            Log.d(Email.LOG_TAG, "MessageViewFragment onActivityCreated");
352        }
353        super.onActivityCreated(savedInstanceState);
354        mController.addResultCallback(mControllerCallback);
355    }
356
357    @Override
358    public void onStart() {
359        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
360            Log.d(Email.LOG_TAG, "MessageViewFragment onStart");
361        }
362        super.onStart();
363    }
364
365    @Override
366    public void onResume() {
367        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
368            Log.d(Email.LOG_TAG, "MessageViewFragment onResume");
369        }
370        super.onResume();
371
372        mResumed = true;
373        if (isMessageSpecified()) {
374            if (mLoadWhenResumed) {
375                loadMessageIfResumed();
376            } else {
377                // This means, the user comes back from other (full-screen) activities.
378                // In this case we've already loaded the content, so don't load it again,
379                // which results in resetting all view state, including WebView zoom/pan
380                // and the current tab.
381            }
382        }
383    }
384
385    @Override
386    public void onPause() {
387        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
388            Log.d(Email.LOG_TAG, "MessageViewFragment onPause");
389        }
390        mResumed = false;
391        super.onPause();
392    }
393
394    @Override
395    public void onStop() {
396        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
397            Log.d(Email.LOG_TAG, "MessageViewFragment onStop");
398        }
399        super.onStop();
400    }
401
402    @Override
403    public void onDestroy() {
404        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
405            Log.d(Email.LOG_TAG, "MessageViewFragment onDestroy");
406        }
407        mCallback.onMessageViewGone();
408        mController.removeResultCallback(mControllerCallback);
409        clearContent();
410        mMessageContentView.destroy();
411        mMessageContentView = null;
412        super.onDestroy();
413    }
414
415    @Override
416    public void onSaveInstanceState(Bundle outState) {
417        if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
418            Log.d(Email.LOG_TAG, "MessageViewFragment onSaveInstanceState");
419        }
420        super.onSaveInstanceState(outState);
421    }
422
423    public void setCallback(Callback callback) {
424        mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback;
425    }
426
427    private void cancelAllTasks() {
428        mMessageObserver.unregister();
429        Utility.cancelTaskInterrupt(mLoadMessageTask);
430        mLoadMessageTask = null;
431        Utility.cancelTaskInterrupt(mReloadMessageTask);
432        mReloadMessageTask = null;
433        Utility.cancelTaskInterrupt(mLoadBodyTask);
434        mLoadBodyTask = null;
435        Utility.cancelTaskInterrupt(mLoadAttachmentsTask);
436        mLoadAttachmentsTask = null;
437    }
438
439    /**
440     * Subclass returns true if which message to open is already specified by the activity.
441     */
442    protected abstract boolean isMessageSpecified();
443
444    protected final Controller getController() {
445        return mController;
446    }
447
448    protected final Callback getCallback() {
449        return mCallback;
450    }
451
452    protected final Message getMessage() {
453        return mMessage;
454    }
455
456    protected final boolean isMessageOpen() {
457        return mMessage != null;
458    }
459
460    /**
461     * Returns the account id of the current message, or -1 if unknown (message not open yet, or
462     * viewing an EML message).
463     */
464    public long getAccountId() {
465        return mAccountId;
466    }
467
468    /**
469     * Clear all the content -- should be called when the fragment is hidden.
470     */
471    public void clearContent() {
472        cancelAllTasks();
473        resetView();
474    }
475
476    protected final void loadMessageIfResumed() {
477        if (!mResumed) {
478            mLoadWhenResumed = true;
479            return;
480        }
481        mLoadWhenResumed = false;
482        cancelAllTasks();
483        resetView();
484        mLoadMessageTask = new LoadMessageTask(true);
485        mLoadMessageTask.execute();
486    }
487
488    /**
489     * Show/hide the content.  We hide all the content (except for the bottom buttons) when loading,
490     * to avoid flicker.
491     */
492    private void showContent(boolean showContent, boolean showProgressWhenHidden) {
493        if (mLoadingProgress == null) {
494            // Phone UI doesn't have it yet.
495            // TODO Add loading_progress and main_panel to the phone layout too.
496        } else {
497            makeVisible(mMainView, showContent);
498            makeVisible(mLoadingProgress, !showContent && showProgressWhenHidden);
499        }
500    }
501
502    protected void resetView() {
503        showContent(false, false);
504        setCurrentTab(TAB_MESSAGE);
505        updateTabFlags(0);
506        if (mMessageContentView != null) {
507            mMessageContentView.getSettings().setBlockNetworkLoads(true);
508            mMessageContentView.scrollTo(0, 0);
509            mMessageContentView.clearView();
510
511            // Dynamic configuration of WebView
512            final WebSettings settings = mMessageContentView.getSettings();
513            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
514            mMessageContentView.setInitialScale(getWebViewZoom());
515        }
516        mAttachmentsScroll.scrollTo(0, 0);
517        mInviteScroll.scrollTo(0, 0);
518        mAttachments.removeAllViews();
519        mAttachments.setVisibility(View.GONE);
520        initContactStatusViews();
521    }
522
523    /**
524     * Returns the zoom scale (in percent) which is a combination of the user setting
525     * (tiny, small, normal, large, huge) and the device density. The intention
526     * is for the text to be physically equal in size over different density
527     * screens.
528     */
529    private int getWebViewZoom() {
530        float density = mContext.getResources().getDisplayMetrics().density;
531        int zoom = Preferences.getPreferences(mContext).getTextZoom();
532        return (int) (ZOOM_SCALE_ARRAY[zoom] * density * 100);
533    }
534
535    private void initContactStatusViews() {
536        mContactStatusState = CONTACT_STATUS_STATE_UNLOADED;
537        mQuickContactLookupUri = null;
538        mSenderPresenceView.setImageResource(ContactStatusLoader.PRESENCE_UNKNOWN_RESOURCE_ID);
539        showDefaultQuickContactBadgeImage();
540    }
541
542    private void showDefaultQuickContactBadgeImage() {
543        mFromBadge.setImageResource(R.drawable.ic_contact_picture);
544    }
545
546    protected final void addTabFlags(int tabFlags) {
547        updateTabFlags(mTabFlags | tabFlags);
548    }
549
550    private final void clearTabFlags(int tabFlags) {
551        updateTabFlags(mTabFlags & ~tabFlags);
552    }
553
554    private void setAttachmentCount(int count) {
555        mAttachmentCount = count;
556        if (mAttachmentCount > 0) {
557            addTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
558        } else {
559            clearTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
560        }
561    }
562
563    private static void makeVisible(View v, boolean visible) {
564        v.setVisibility(visible ? View.VISIBLE : View.GONE);
565    }
566
567    /**
568     * Update the visual of the tabs.  (visibility, text, etc)
569     */
570    private void updateTabFlags(int tabFlags) {
571        mTabFlags = tabFlags;
572        mTabSection.setVisibility(tabFlags == 0 ? View.GONE : View.VISIBLE);
573        if (tabFlags == 0) {
574            return;
575        }
576        boolean messageTabVisible = (tabFlags & (TAB_FLAGS_HAS_INVITE | TAB_FLAGS_HAS_ATTACHMENT))
577                != 0;
578        makeVisible(mMessageTab, messageTabVisible);
579        makeVisible(mInviteTab, (tabFlags & TAB_FLAGS_HAS_INVITE) != 0);
580        makeVisible(mAttachmentTab, (tabFlags & TAB_FLAGS_HAS_ATTACHMENT) != 0);
581
582        final boolean hasPictures = (tabFlags & TAB_FLAGS_HAS_PICTURES) != 0;
583        final boolean pictureLoaded = (tabFlags & TAB_FLAGS_PICTURE_LOADED) != 0;
584        makeVisible(mShowPicturesTab, hasPictures && !pictureLoaded);
585
586        mAttachmentTab.setText(mContext.getResources().getQuantityString(
587                R.plurals.message_view_show_attachments_action,
588                mAttachmentCount, mAttachmentCount));
589    }
590
591    /**
592     * Set the current tab.
593     *
594     * @param tab any of {@link #TAB_MESSAGE}, {@link #TAB_ATTACHMENT} or {@link #TAB_INVITE}.
595     */
596    private void setCurrentTab(int tab) {
597        mCurrentTab = tab;
598        if (mMessageContentView != null) {
599            makeVisible(mMessageContentView, tab == TAB_MESSAGE);
600        }
601        mMessageTab.setSelected(tab == TAB_MESSAGE);
602
603        makeVisible(mAttachmentsScroll, tab == TAB_ATTACHMENT);
604        mAttachmentTab.setSelected(tab == TAB_ATTACHMENT);
605
606        makeVisible(mInviteScroll, tab == TAB_INVITE);
607        mInviteTab.setSelected(tab == TAB_INVITE);
608    }
609
610    /**
611     * Handle clicks on sender, which shows {@link QuickContact} or prompts to add
612     * the sender as a contact.
613     */
614    private void onClickSender() {
615        final Address senderEmail = Address.unpackFirst(mMessage.mFrom);
616        if (senderEmail == null) return;
617
618        if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED) {
619            // Status not loaded yet.
620            mContactStatusState = CONTACT_STATUS_STATE_UNLOADED_TRIGGERED;
621            return;
622        }
623        if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED) {
624            return; // Already clicked, and waiting for the data.
625        }
626
627        if (mQuickContactLookupUri != null) {
628            QuickContact.showQuickContact(mContext, mFromBadge, mQuickContactLookupUri,
629                        QuickContact.MODE_LARGE, null);
630        } else {
631            // No matching contact, ask user to create one
632            final Uri mailUri = Uri.fromParts("mailto", senderEmail.getAddress(), null);
633            final Intent intent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT,
634                    mailUri);
635
636            // Pass along full E-mail string for possible create dialog
637            intent.putExtra(ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION,
638                    senderEmail.toString());
639
640            // Only provide personal name hint if we have one
641            final String senderPersonal = senderEmail.getPersonal();
642            if (!TextUtils.isEmpty(senderPersonal)) {
643                intent.putExtra(ContactsContract.Intents.Insert.NAME, senderPersonal);
644            }
645            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
646
647            startActivity(intent);
648        }
649    }
650
651    private static class ContactStatusLoaderCallbacks
652            implements LoaderCallbacks<ContactStatusLoader.Result> {
653        private static final String BUNDLE_EMAIL_ADDRESS = "email";
654        private final MessageViewFragmentBase mFragment;
655
656        public ContactStatusLoaderCallbacks(MessageViewFragmentBase fragment) {
657            mFragment = fragment;
658        }
659
660        public static Bundle createArguments(String emailAddress) {
661            Bundle b = new Bundle();
662            b.putString(BUNDLE_EMAIL_ADDRESS, emailAddress);
663            return b;
664        }
665
666        @Override
667        public Loader<ContactStatusLoader.Result> onCreateLoader(int id, Bundle args) {
668            return new ContactStatusLoader(mFragment.mContext,
669                    args.getString(BUNDLE_EMAIL_ADDRESS));
670        }
671
672        @Override
673        public void onLoadFinished(Loader<ContactStatusLoader.Result> loader,
674                ContactStatusLoader.Result result) {
675            boolean triggered =
676                    (mFragment.mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED);
677            mFragment.mContactStatusState = CONTACT_STATUS_STATE_LOADED;
678            mFragment.mQuickContactLookupUri = result.mLookupUri;
679            mFragment.mSenderPresenceView.setImageResource(result.mPresenceResId);
680            if (result.mPhoto != null) { // photo will be null if unknown.
681                mFragment.mFromBadge.setImageBitmap(result.mPhoto);
682            }
683            if (triggered) {
684                mFragment.onClickSender();
685            }
686        }
687
688        @Override
689        public void onLoaderReset(Loader<ContactStatusLoader.Result> loader) {
690        }
691    }
692
693    private void onSaveAttachment(AttachmentInfo info) {
694        if (!Utility.isExternalStorageMounted()) {
695            /*
696             * Abort early if there's no place to save the attachment. We don't want to spend
697             * the time downloading it and then abort.
698             */
699            Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
700            return;
701        }
702        Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.attachmentId);
703        Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);
704
705        try {
706            File downloads = Environment.getExternalStoragePublicDirectory(
707                    Environment.DIRECTORY_DOWNLOADS);
708            downloads.mkdirs();
709            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
710            Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(
711                    mContext.getContentResolver(), attachmentUri);
712            InputStream in = mContext.getContentResolver().openInputStream(contentUri);
713            OutputStream out = new FileOutputStream(file);
714            IOUtils.copy(in, out);
715            out.flush();
716            out.close();
717            in.close();
718
719            Utility.showToast(getActivity(), String.format(
720                    mContext.getString(R.string.message_view_status_attachment_saved),
721                    file.getName()));
722            MediaOpener.scanAndOpen(getActivity(), file);
723        } catch (IOException ioe) {
724            Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
725        }
726    }
727
728    private void onViewAttachment(AttachmentInfo info) {
729        Intent intent = getAttachmentIntent(info);
730        try {
731            startActivity(intent);
732        } catch (ActivityNotFoundException e) {
733            Utility.showToast(getActivity(), R.string.message_view_display_attachment_toast);
734        }
735    }
736
737    /**
738     * Returns an <code>Intent</code> to load the given attachment.
739     */
740    private Intent getAttachmentIntent(AttachmentInfo info) {
741        Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, info.attachmentId);
742        Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(
743                mContext.getContentResolver(), attachmentUri);
744        Intent intent = new Intent(Intent.ACTION_VIEW);
745        intent.setData(contentUri);
746        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
747                        | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
748        return intent;
749    }
750
751    private void onLoadAttachment(final AttachmentInfo attachment) {
752        attachment.loadButton.setVisibility(View.GONE);
753        // If there's nothing in the download queue, we'll probably start right away so wait a
754        // second before showing the cancel button
755        if (AttachmentDownloadService.getQueueSize() == 0) {
756            // Set to invisible; if the button is still in this state one second from now, we'll
757            // assume the download won't start right away, and we make the cancel button visible
758            attachment.cancelButton.setVisibility(View.GONE);
759            // Create the timed task that will change the button state
760            new AsyncTask<Void, Void, Void>() {
761                @Override
762                protected Void doInBackground(Void... params) {
763                    try {
764                        Thread.sleep(1000L);
765                    } catch (InterruptedException e) { }
766                    return null;
767                }
768                @Override
769                protected void onPostExecute(Void result) {
770                    // If the timeout completes and the attachment has not loaded, show cancel
771                    if (!attachment.isLoaded) {
772                        attachment.cancelButton.setVisibility(View.VISIBLE);
773                    }
774                }
775            }.execute();
776        } else {
777            attachment.cancelButton.setVisibility(View.VISIBLE);
778        }
779        ProgressBar bar = attachment.progressView;
780        bar.setVisibility(View.VISIBLE);
781        bar.setIndeterminate(true);
782        mController.loadAttachment(attachment.attachmentId, mMessageId, mAccountId);
783    }
784
785    private void onCancelAttachment(AttachmentInfo attachment) {
786        // Don't change button states if we couldn't cancel the download
787        if (AttachmentDownloadService.cancelQueuedAttachment(attachment.attachmentId)) {
788            attachment.loadButton.setVisibility(View.VISIBLE);
789            attachment.cancelButton.setVisibility(View.GONE);
790            ProgressBar bar = attachment.progressView;
791            bar.setVisibility(View.INVISIBLE);
792        }
793    }
794
795    /**
796     * Called by ControllerResults. Show the "View" and "Save" buttons; hide "Load" and "Stop"
797     *
798     * @param attachmentId the attachment that was just downloaded
799     */
800    private void doFinishLoadAttachment(long attachmentId) {
801        AttachmentInfo info = findAttachmentInfo(attachmentId);
802        if (info != null) {
803            info.isLoaded = true;
804
805            info.loadButton.setVisibility(View.GONE);
806            info.cancelButton.setVisibility(View.GONE);
807
808            boolean showSave = info.allowSave && !TextUtils.isEmpty(info.name);
809            boolean showView = info.allowView;
810            info.saveButton.setVisibility(showSave ? View.VISIBLE : View.GONE);
811            info.viewButton.setVisibility(showView ? View.VISIBLE : View.GONE);
812        }
813    }
814
815    private void onShowPicturesInHtml() {
816        if (mMessageContentView != null) {
817            mMessageContentView.getSettings().setBlockNetworkLoads(false);
818            if (mHtmlTextWebView != null) {
819                mMessageContentView.loadDataWithBaseURL("email://", mHtmlTextWebView,
820                                                        "text/html", "utf-8", null);
821            }
822            addTabFlags(TAB_FLAGS_PICTURE_LOADED);
823        }
824    }
825
826    private void onShowDetails() {
827        if (mMessage == null) {
828            return; // shouldn't happen
829        }
830        String subject = mMessage.mSubject;
831        String date = formatDate(mMessage.mTimeStamp, true);
832        String from = Address.toString(Address.unpack(mMessage.mFrom));
833        String to = Address.toString(Address.unpack(mMessage.mTo));
834        String cc = Address.toString(Address.unpack(mMessage.mCc));
835        String bcc = Address.toString(Address.unpack(mMessage.mBcc));
836        MessageViewMessageDetailsDialog dialog = MessageViewMessageDetailsDialog.newInstance(
837                getActivity(), subject, date, from, to, cc, bcc);
838        dialog.show(getActivity().getFragmentManager(), null);
839    }
840
841    @Override
842    public void onClick(View view) {
843        if (!isMessageOpen()) {
844            return; // Ignore.
845        }
846        switch (view.getId()) {
847            case R.id.from_name:
848            case R.id.from_address:
849            case R.id.badge:
850            case R.id.presence:
851                onClickSender();
852                break;
853            case R.id.load:
854                onLoadAttachment((AttachmentInfo) view.getTag());
855                break;
856            case R.id.save:
857                onSaveAttachment((AttachmentInfo) view.getTag());
858                break;
859            case R.id.view:
860                onViewAttachment((AttachmentInfo) view.getTag());
861                break;
862            case R.id.cancel:
863                onCancelAttachment((AttachmentInfo) view.getTag());
864                break;
865            case R.id.show_message:
866                setCurrentTab(TAB_MESSAGE);
867                break;
868            case R.id.show_invite:
869                setCurrentTab(TAB_INVITE);
870                break;
871            case R.id.show_attachments:
872                setCurrentTab(TAB_ATTACHMENT);
873                break;
874            case R.id.show_pictures:
875                onShowPicturesInHtml();
876                break;
877            case R.id.show_details:
878                onShowDetails();
879                break;
880        }
881    }
882
883    /**
884     * Start loading contact photo and presence.
885     */
886    private void queryContactStatus() {
887        initContactStatusViews(); // Initialize the state, just in case.
888
889        // Find the sender email address, and start presence check.
890        if (mMessage != null) {
891            Address sender = Address.unpackFirst(mMessage.mFrom);
892            if (sender != null) {
893                String email = sender.getAddress();
894                if (email != null) {
895                    getLoaderManager().restartLoader(PHOTO_LOADER_ID,
896                            ContactStatusLoaderCallbacks.createArguments(email),
897                            new ContactStatusLoaderCallbacks(this));
898                }
899            }
900        }
901    }
902
903    /**
904     * Called by {@link LoadMessageTask} and {@link ReloadMessageTask} to load a message in a
905     * subclass specific way.
906     *
907     * NOTE This method is called on a worker thread!  Implementations must properly synchronize
908     * when accessing members.  This method may be called after or even at the same time as
909     * {@link #clearContent()}.
910     *
911     * @param activity the parent activity.  Subclass use it as a context, and to show a toast.
912     */
913    protected abstract Message openMessageSync(Activity activity);
914
915    /**
916     * Async task for loading a single message outside of the UI thread
917     */
918    private class LoadMessageTask extends AsyncTask<Void, Void, Message> {
919
920        private final boolean mOkToFetch;
921        private int mMailboxType;
922
923        /**
924         * Special constructor to cache some local info
925         */
926        public LoadMessageTask(boolean okToFetch) {
927            mOkToFetch = okToFetch;
928        }
929
930        @Override
931        protected Message doInBackground(Void... params) {
932            Activity activity = getActivity();
933            Message message = null;
934            if (activity != null) {
935                message = openMessageSync(activity);
936            }
937            if (message != null) {
938                mMailboxType = Mailbox.getMailboxType(mContext, message.mMailboxKey);
939                if (mMailboxType == -1) {
940                    message = null; // mailbox removed??
941                }
942            }
943            return message;
944        }
945
946        @Override
947        protected void onPostExecute(Message message) {
948            if (isCancelled()) {
949                return;
950            }
951            if (message == null) {
952                resetView();
953                mCallback.onMessageNotExists();
954                return;
955            }
956            mMessageId = message.mId;
957
958            reloadUiFromMessage(message, mOkToFetch);
959            queryContactStatus();
960            onMessageShown(mMessageId, mMailboxType);
961        }
962    }
963
964    /**
965     * Kicked by {@link MessageObserver}.  Reload the message and update the views.
966     */
967    private class ReloadMessageTask extends AsyncTask<Void, Void, Message> {
968        @Override
969        protected Message doInBackground(Void... params) {
970            if (!isMessageSpecified()) { // just in case
971                return null;
972            }
973            Activity activity = getActivity();
974            if (activity == null) {
975                return null;
976            } else {
977                return openMessageSync(activity);
978            }
979        }
980
981        @Override
982        protected void onPostExecute(Message message) {
983            if (isCancelled()) {
984                return;
985            }
986            if (message == null || message.mMailboxKey != mMessage.mMailboxKey) {
987                // Message deleted or moved.
988                mCallback.onMessageNotExists();
989                return;
990            }
991            mMessage = message;
992            updateHeaderView(mMessage);
993        }
994    }
995
996    /**
997     * Called when a message is shown to the user.
998     */
999    protected void onMessageShown(long messageId, int mailboxType) {
1000        mCallback.onMessageViewShown(mailboxType);
1001    }
1002
1003    /**
1004     * Called when the message body is loaded.
1005     */
1006    protected void onPostLoadBody() {
1007    }
1008
1009    /**
1010     * Async task for loading a single message body outside of the UI thread
1011     */
1012    private class LoadBodyTask extends AsyncTask<Void, Void, String[]> {
1013
1014        private long mId;
1015        private boolean mErrorLoadingMessageBody;
1016
1017        /**
1018         * Special constructor to cache some local info
1019         */
1020        public LoadBodyTask(long messageId) {
1021            mId = messageId;
1022        }
1023
1024        @Override
1025        protected String[] doInBackground(Void... params) {
1026            try {
1027                String text = null;
1028                String html = Body.restoreBodyHtmlWithMessageId(mContext, mId);
1029                if (html == null) {
1030                    text = Body.restoreBodyTextWithMessageId(mContext, mId);
1031                }
1032                return new String[] { text, html };
1033            } catch (RuntimeException re) {
1034                // This catches SQLiteException as well as other RTE's we've seen from the
1035                // database calls, such as IllegalStateException
1036                Log.d(Email.LOG_TAG, "Exception while loading message body", re);
1037                mErrorLoadingMessageBody = true;
1038                return null;
1039            }
1040        }
1041
1042        @Override
1043        protected void onPostExecute(String[] results) {
1044            if (results == null || isCancelled()) {
1045                if (mErrorLoadingMessageBody) {
1046                    Utility.showToast(getActivity(), R.string.error_loading_message_body);
1047                }
1048                resetView();
1049                return;
1050            }
1051            reloadUiFromBody(results[0], results[1]);    // text, html
1052            onPostLoadBody();
1053        }
1054    }
1055
1056    /**
1057     * Async task for loading attachments
1058     *
1059     * Note:  This really should only be called when the message load is complete - or, we should
1060     * leave open a listener so the attachments can fill in as they are discovered.  In either case,
1061     * this implementation is incomplete, as it will fail to refresh properly if the message is
1062     * partially loaded at this time.
1063     */
1064    private class LoadAttachmentsTask extends AsyncTask<Long, Void, Attachment[]> {
1065        @Override
1066        protected Attachment[] doInBackground(Long... messageIds) {
1067            return Attachment.restoreAttachmentsWithMessageId(mContext, messageIds[0]);
1068        }
1069
1070        @Override
1071        protected void onPostExecute(Attachment[] attachments) {
1072            try {
1073                if (isCancelled() || attachments == null) {
1074                    return;
1075                }
1076                boolean htmlChanged = false;
1077                int numDisplayedAttachments = 0;
1078                for (Attachment attachment : attachments) {
1079                    if (mHtmlTextRaw != null && attachment.mContentId != null
1080                            && attachment.mContentUri != null) {
1081                        // for html body, replace CID for inline images
1082                        // Regexp which matches ' src="cid:contentId"'.
1083                        String contentIdRe =
1084                            "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
1085                        String srcContentUri = " src=\"" + attachment.mContentUri + "\"";
1086                        mHtmlTextRaw = mHtmlTextRaw.replaceAll(contentIdRe, srcContentUri);
1087                        htmlChanged = true;
1088                    } else {
1089                        addAttachment(attachment);
1090                        numDisplayedAttachments++;
1091                    }
1092                }
1093                setAttachmentCount(numDisplayedAttachments);
1094                mHtmlTextWebView = mHtmlTextRaw;
1095                mHtmlTextRaw = null;
1096                if (htmlChanged && mMessageContentView != null) {
1097                    mMessageContentView.loadDataWithBaseURL("email://", mHtmlTextWebView,
1098                                                            "text/html", "utf-8", null);
1099                }
1100            } finally {
1101                showContent(true, false);
1102            }
1103        }
1104    }
1105
1106    private Bitmap getPreviewIcon(AttachmentInfo attachment) {
1107        try {
1108            return BitmapFactory.decodeStream(
1109                    mContext.getContentResolver().openInputStream(
1110                            AttachmentProvider.getAttachmentThumbnailUri(
1111                                    mAccountId, attachment.attachmentId,
1112                                    PREVIEW_ICON_WIDTH,
1113                                    PREVIEW_ICON_HEIGHT)));
1114        } catch (Exception e) {
1115            Log.d(Email.LOG_TAG, "Attachment preview failed with exception " + e.getMessage());
1116            return null;
1117        }
1118    }
1119
1120    private void updateAttachmentThumbnail(long attachmentId) {
1121        for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
1122            AttachmentInfo attachment = (AttachmentInfo) mAttachments.getChildAt(i).getTag();
1123            if (attachment.attachmentId == attachmentId) {
1124                Bitmap previewIcon = getPreviewIcon(attachment);
1125                if (previewIcon != null) {
1126                    attachment.iconView.setImageBitmap(previewIcon);
1127                }
1128                return;
1129            }
1130        }
1131    }
1132
1133    /**
1134     * Copy data from a cursor-refreshed attachment into the UI.  Called from UI thread.
1135     *
1136     * @param attachment A single attachment loaded from the provider
1137     */
1138    private void addAttachment(Attachment attachment) {
1139        AttachmentInfo attachmentInfo = new AttachmentInfo();
1140        attachmentInfo.size = attachment.mSize;
1141        attachmentInfo.contentType =
1142                AttachmentProvider.inferMimeType(attachment.mFileName, attachment.mMimeType);
1143        attachmentInfo.name = attachment.mFileName;
1144        attachmentInfo.attachmentId = attachment.mId;
1145        attachmentInfo.allowView = true;
1146        attachmentInfo.allowSave = true;
1147        attachmentInfo.isLoaded = false;
1148
1149        LayoutInflater inflater = getActivity().getLayoutInflater();
1150        View view = inflater.inflate(R.layout.message_view_attachment, null);
1151
1152        TextView attachmentName = (TextView)view.findViewById(R.id.attachment_name);
1153        TextView attachmentInfoView = (TextView)view.findViewById(R.id.attachment_info);
1154        ImageView attachmentIcon = (ImageView)view.findViewById(R.id.attachment_icon);
1155        Button attachmentView = (Button)view.findViewById(R.id.view);
1156        Button attachmentSave = (Button)view.findViewById(R.id.save);
1157        Button attachmentLoad = (Button)view.findViewById(R.id.load);
1158        Button attachmentCancel = (Button)view.findViewById(R.id.cancel);
1159        ProgressBar attachmentProgress = (ProgressBar)view.findViewById(R.id.progress);
1160
1161        // Check for acceptable / unacceptable attachments by MIME-type
1162        String contentType = attachmentInfo.contentType;
1163        if ((!MimeUtility.mimeTypeMatches(contentType, Email.ACCEPTABLE_ATTACHMENT_VIEW_TYPES)) ||
1164            (MimeUtility.mimeTypeMatches(contentType, Email.UNACCEPTABLE_ATTACHMENT_VIEW_TYPES))) {
1165            attachmentInfo.allowView = false;
1166        }
1167
1168        // Check for unacceptable attachments by filename extension; hide both buttons
1169        String extension = AttachmentProvider.getFilenameExtension(attachmentInfo.name);
1170        if (!TextUtils.isEmpty(extension) &&
1171                Utility.arrayContains(Email.UNACCEPTABLE_ATTACHMENT_EXTENSIONS, extension)) {
1172            attachmentInfo.allowView = false;
1173            attachmentInfo.allowSave = false;
1174        }
1175
1176        // Check for installable attachments by filename extension; hide both buttons
1177        extension = AttachmentProvider.getFilenameExtension(attachmentInfo.name);
1178        if (!TextUtils.isEmpty(extension) &&
1179                Utility.arrayContains(Email.INSTALLABLE_ATTACHMENT_EXTENSIONS, extension)) {
1180            int sideloadEnabled;
1181            sideloadEnabled = Settings.Secure.getInt(mContext.getContentResolver(),
1182                    Settings.Secure.INSTALL_NON_MARKET_APPS, 0 /* sideload disabled */);
1183            // TODO Allow showing an "install" button
1184            attachmentInfo.allowView = false;
1185            attachmentInfo.allowSave = (sideloadEnabled == 1);
1186        }
1187
1188        // File size exceeded;  Hide both buttons
1189        // The size limit is overridden when on a wifi connection - any size is OK
1190        if (attachmentInfo.size > Email.MAX_ATTACHMENT_DOWNLOAD_SIZE) {
1191            ConnectivityManager cm = (ConnectivityManager)
1192                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
1193            NetworkInfo network = cm.getActiveNetworkInfo();
1194            if (network == null || network.getType() != ConnectivityManager.TYPE_WIFI) {
1195                attachmentInfo.allowView = false;
1196                attachmentInfo.allowSave = false;
1197            }
1198        }
1199
1200        // No activity to view the attachment; Hide both buttons
1201        if (!isAttachmentViewerInstalled(attachmentInfo)) {
1202            attachmentInfo.allowView = false;
1203            attachmentInfo.allowSave = false;
1204        }
1205
1206        // Don't enable the "save" button if we've got no place to save the file
1207        if (!Utility.isExternalStorageMounted()) {
1208            attachmentInfo.allowSave = false;
1209        }
1210
1211        if (!attachmentInfo.allowView) {
1212            attachmentView.setVisibility(View.GONE);
1213        }
1214        if (!attachmentInfo.allowSave) {
1215            attachmentSave.setVisibility(View.GONE);
1216        }
1217
1218        attachmentInfo.viewButton = attachmentView;
1219        attachmentInfo.saveButton = attachmentSave;
1220        attachmentInfo.loadButton = attachmentLoad;
1221        attachmentInfo.cancelButton = attachmentCancel;
1222        attachmentInfo.iconView = attachmentIcon;
1223        attachmentInfo.progressView = attachmentProgress;
1224
1225        if (!attachmentInfo.allowView && !attachmentInfo.allowSave) {
1226            // This attachment may never be viewed or saved, so block everything
1227            attachmentProgress.setVisibility(View.GONE);
1228            attachmentView.setVisibility(View.GONE);
1229            attachmentSave.setVisibility(View.GONE);
1230            attachmentLoad.setVisibility(View.GONE);
1231            attachmentCancel.setVisibility(View.GONE);
1232            // TODO: Maybe show a little icon to denote blocked download
1233        } else if (Utility.attachmentExists(mContext, attachment)) {
1234            // If the attachment is loaded, show 100% progress
1235            // Note that for POP3 messages, the user will only see "Open" and "Save",
1236            // because the entire message is loaded before being shown.
1237            attachmentInfo.isLoaded = true;
1238
1239            // Hide "Load", show "View" and "Save"
1240            attachmentProgress.setVisibility(View.VISIBLE);
1241            attachmentProgress.setProgress(100);
1242            if (attachmentInfo.allowSave) {
1243                attachmentSave.setVisibility(View.VISIBLE);
1244            }
1245            if (attachmentInfo.allowView) {
1246                attachmentView.setVisibility(View.VISIBLE);
1247            }
1248            attachmentLoad.setVisibility(View.GONE);
1249            attachmentCancel.setVisibility(View.GONE);
1250
1251            Bitmap previewIcon = getPreviewIcon(attachmentInfo);
1252            if (previewIcon != null) {
1253                attachmentIcon.setImageBitmap(previewIcon);
1254            }
1255        } else {
1256            // The attachment is not loaded, so present UI to start downloading it
1257
1258            // Show "Load"; hide "View" and "Save"
1259            attachmentSave.setVisibility(View.GONE);
1260            attachmentView.setVisibility(View.GONE);
1261
1262            // If the attachment is queued, show the indeterminate progress bar.  From this point,.
1263            // any progress changes will cause this to be replaced by the normal progress bar
1264            if (AttachmentDownloadService.isAttachmentQueued(attachment.mId)){
1265                attachmentProgress.setVisibility(View.VISIBLE);
1266                attachmentProgress.setIndeterminate(true);
1267                attachmentLoad.setVisibility(View.GONE);
1268                attachmentCancel.setVisibility(View.VISIBLE);
1269            } else {
1270                attachmentLoad.setVisibility(View.VISIBLE);
1271                attachmentCancel.setVisibility(View.GONE);
1272            }
1273        }
1274
1275        view.setTag(attachmentInfo);
1276        attachmentView.setOnClickListener(this);
1277        attachmentView.setTag(attachmentInfo);
1278        attachmentSave.setOnClickListener(this);
1279        attachmentSave.setTag(attachmentInfo);
1280        attachmentLoad.setOnClickListener(this);
1281        attachmentLoad.setTag(attachmentInfo);
1282        attachmentCancel.setOnClickListener(this);
1283        attachmentCancel.setTag(attachmentInfo);
1284
1285        attachmentName.setText(attachmentInfo.name);
1286        attachmentInfoView.setText(Utility.formatSize(mContext, attachmentInfo.size));
1287
1288        mAttachments.addView(view);
1289        mAttachments.setVisibility(View.VISIBLE);
1290    }
1291
1292    /**
1293     * Returns whether or not there is an Activity installed that can handle the given attachment.
1294     */
1295    private boolean isAttachmentViewerInstalled(AttachmentInfo info) {
1296        Intent intent = getAttachmentIntent(info);
1297        PackageManager pm = mContext.getPackageManager();
1298        List<ResolveInfo> activityList = pm.queryIntentActivities(intent, 0);
1299        return (activityList.size() > 0);
1300    }
1301
1302    /**
1303     * Reload the UI from a provider cursor.  {@link LoadMessageTask#onPostExecute} calls it.
1304     *
1305     * Update the header views, and start loading the body.
1306     *
1307     * @param message A copy of the message loaded from the database
1308     * @param okToFetch If true, and message is not fully loaded, it's OK to fetch from
1309     * the network.  Use false to prevent looping here.
1310     */
1311    protected void reloadUiFromMessage(Message message, boolean okToFetch) {
1312        mMessage = message;
1313        mAccountId = message.mAccountKey;
1314
1315        mMessageObserver.register(ContentUris.withAppendedId(Message.CONTENT_URI, mMessage.mId));
1316
1317        updateHeaderView(mMessage);
1318
1319        // Handle partially-loaded email, as follows:
1320        // 1. Check value of message.mFlagLoaded
1321        // 2. If != LOADED, ask controller to load it
1322        // 3. Controller callback (after loaded) should trigger LoadBodyTask & LoadAttachmentsTask
1323        // 4. Else start the loader tasks right away (message already loaded)
1324        if (okToFetch && message.mFlagLoaded != Message.FLAG_LOADED_COMPLETE) {
1325            mControllerCallback.getWrappee().setWaitForLoadMessageId(message.mId);
1326            mController.loadMessageForView(message.mId);
1327        } else {
1328            mControllerCallback.getWrappee().setWaitForLoadMessageId(-1);
1329            // Ask for body
1330            mLoadBodyTask = new LoadBodyTask(message.mId);
1331            mLoadBodyTask.execute();
1332        }
1333    }
1334
1335    protected void updateHeaderView(Message message) {
1336        mSubjectView.setText(message.mSubject);
1337        final Address from = Address.unpackFirst(message.mFrom);
1338
1339        // Set sender address/display name
1340        // Note we set " " for empty field, so TextView's won't get squashed.
1341        // Otherwise their height will be 0, which breaks the layout.
1342        if (from != null) {
1343            final String fromFriendly = from.toFriendly();
1344            final String fromAddress = from.getAddress();
1345            mFromNameView.setText(fromFriendly);
1346            mFromAddressView.setText(fromFriendly.equals(fromAddress) ? " " : fromAddress);
1347        } else {
1348            mFromNameView.setText(" ");
1349            mFromAddressView.setText(" ");
1350        }
1351        mDateTimeView.setText(formatDate(message.mTimeStamp, false));
1352
1353        // To/Cc/Bcc
1354        final Resources res = mContext.getResources();
1355        final SpannableStringBuilder ssb = new SpannableStringBuilder();
1356        final String friendlyTo = Address.toFriendly(Address.unpack(message.mTo));
1357        final String friendlyCc = Address.toFriendly(Address.unpack(message.mCc));
1358        final String friendlyBcc = Address.toFriendly(Address.unpack(message.mBcc));
1359
1360        if (!TextUtils.isEmpty(friendlyTo)) {
1361            Utility.appendBold(ssb, res.getString(R.string.message_view_to_label));
1362            ssb.append(" ");
1363            ssb.append(friendlyTo);
1364        }
1365        if (!TextUtils.isEmpty(friendlyCc)) {
1366            ssb.append("  ");
1367            Utility.appendBold(ssb, res.getString(R.string.message_view_cc_label));
1368            ssb.append(" ");
1369            ssb.append(friendlyCc);
1370        }
1371        if (!TextUtils.isEmpty(friendlyBcc)) {
1372            ssb.append("  ");
1373            Utility.appendBold(ssb, res.getString(R.string.message_view_bcc_label));
1374            ssb.append(" ");
1375            ssb.append(friendlyBcc);
1376        }
1377        mAddressesView.setText(ssb);
1378    }
1379
1380    private String formatDate(long millis, boolean withYear) {
1381        StringBuilder sb = new StringBuilder();
1382        Formatter formatter = new Formatter(sb);
1383        DateUtils.formatDateRange(mContext, formatter, millis, millis,
1384                DateUtils.FORMAT_SHOW_DATE
1385                | DateUtils.FORMAT_ABBREV_ALL
1386                | DateUtils.FORMAT_SHOW_TIME
1387                | (withYear ? DateUtils.FORMAT_SHOW_YEAR : DateUtils.FORMAT_NO_YEAR));
1388        return sb.toString();
1389    }
1390
1391    /**
1392     * Reload the body from the provider cursor.  This must only be called from the UI thread.
1393     *
1394     * @param bodyText text part
1395     * @param bodyHtml html part
1396     *
1397     * TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN??
1398     */
1399    private void reloadUiFromBody(String bodyText, String bodyHtml) {
1400        String text = null;
1401        mHtmlTextRaw = null;
1402        boolean hasImages = false;
1403
1404        if (bodyHtml == null) {
1405            text = bodyText;
1406            /*
1407             * Convert the plain text to HTML
1408             */
1409            StringBuffer sb = new StringBuffer("<html><body>");
1410            if (text != null) {
1411                // Escape any inadvertent HTML in the text message
1412                text = EmailHtmlUtil.escapeCharacterToDisplay(text);
1413                // Find any embedded URL's and linkify
1414                Matcher m = Patterns.WEB_URL.matcher(text);
1415                while (m.find()) {
1416                    int start = m.start();
1417                    /*
1418                     * WEB_URL_PATTERN may match domain part of email address. To detect
1419                     * this false match, the character just before the matched string
1420                     * should not be '@'.
1421                     */
1422                    if (start == 0 || text.charAt(start - 1) != '@') {
1423                        String url = m.group();
1424                        Matcher proto = WEB_URL_PROTOCOL.matcher(url);
1425                        String link;
1426                        if (proto.find()) {
1427                            // This is work around to force URL protocol part be lower case,
1428                            // because WebView could follow only lower case protocol link.
1429                            link = proto.group().toLowerCase() + url.substring(proto.end());
1430                        } else {
1431                            // Patterns.WEB_URL matches URL without protocol part,
1432                            // so added default protocol to link.
1433                            link = "http://" + url;
1434                        }
1435                        String href = String.format("<a href=\"%s\">%s</a>", link, url);
1436                        m.appendReplacement(sb, href);
1437                    }
1438                    else {
1439                        m.appendReplacement(sb, "$0");
1440                    }
1441                }
1442                m.appendTail(sb);
1443            }
1444            sb.append("</body></html>");
1445            text = sb.toString();
1446        } else {
1447            text = bodyHtml;
1448            mHtmlTextRaw = bodyHtml;
1449            hasImages = IMG_TAG_START_REGEX.matcher(text).find();
1450        }
1451
1452        // TODO this is not really accurate.
1453        // - Images aren't the only network resources.  (e.g. CSS)
1454        // - If images are attached to the email and small enough, we download them at once,
1455        //   and won't need network access when they're shown.
1456        if (hasImages) {
1457            addTabFlags(TAB_FLAGS_HAS_PICTURES);
1458        }
1459        if (mMessageContentView != null) {
1460            mMessageContentView.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null);
1461        }
1462
1463        // Ask for attachments after body
1464        mLoadAttachmentsTask = new LoadAttachmentsTask();
1465        mLoadAttachmentsTask.execute(mMessage.mId);
1466
1467        mIsMessageLoadedForTest = true;
1468    }
1469
1470    /**
1471     * Overrides for WebView behaviors.
1472     */
1473    private class CustomWebViewClient extends WebViewClient {
1474        @Override
1475        public boolean shouldOverrideUrlLoading(WebView view, String url) {
1476            return mCallback.onUrlInMessageClicked(url);
1477        }
1478    }
1479
1480    private View findAttachmentView(long attachmentId) {
1481        for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
1482            View view = mAttachments.getChildAt(i);
1483            AttachmentInfo attachment = (AttachmentInfo) view.getTag();
1484            if (attachment.attachmentId == attachmentId) {
1485                return view;
1486            }
1487        }
1488        return null;
1489    }
1490
1491    private AttachmentInfo findAttachmentInfo(long attachmentId) {
1492        View view = findAttachmentView(attachmentId);
1493        if (view != null) {
1494            return (AttachmentInfo)view.getTag();
1495        }
1496        return null;
1497    }
1498
1499    /**
1500     * Controller results listener.  We wrap it with {@link ControllerResultUiThreadWrapper},
1501     * so all methods are called on the UI thread.
1502     */
1503    private class ControllerResults extends Controller.Result {
1504        private long mWaitForLoadMessageId;
1505
1506        public void setWaitForLoadMessageId(long messageId) {
1507            mWaitForLoadMessageId = messageId;
1508        }
1509
1510        @Override
1511        public void loadMessageForViewCallback(MessagingException result, long accountId,
1512                long messageId, int progress) {
1513            if (messageId != mWaitForLoadMessageId) {
1514                // We are not waiting for this message to load, so exit quickly
1515                return;
1516            }
1517            if (result == null) {
1518                switch (progress) {
1519                    case 0:
1520                        mCallback.onLoadMessageStarted();
1521                        // Loading from network -- show the progress icon.
1522                        showContent(false, true);
1523                        break;
1524                    case 100:
1525                        mWaitForLoadMessageId = -1;
1526                        mCallback.onLoadMessageFinished();
1527                        // reload UI and reload everything else too
1528                        // pass false to LoadMessageTask to prevent looping here
1529                        cancelAllTasks();
1530                        mLoadMessageTask = new LoadMessageTask(false);
1531                        mLoadMessageTask.execute();
1532                        break;
1533                    default:
1534                        // do nothing - we don't have a progress bar at this time
1535                        break;
1536                }
1537            } else {
1538                mWaitForLoadMessageId = -1;
1539                String error = mContext.getString(R.string.status_network_error);
1540                mCallback.onLoadMessageError(error);
1541                resetView();
1542            }
1543        }
1544
1545        @Override
1546        public void loadAttachmentCallback(MessagingException result, long accountId,
1547                long messageId, long attachmentId, int progress) {
1548            if (messageId == mMessageId) {
1549                if (result == null) {
1550                    showAttachmentProgress(attachmentId, progress);
1551                    switch (progress) {
1552                        case 100:
1553                            updateAttachmentThumbnail(attachmentId);
1554                            doFinishLoadAttachment(attachmentId);
1555                            break;
1556                        default:
1557                            // do nothing - we don't have a progress bar at this time
1558                            break;
1559                    }
1560                } else {
1561                    AttachmentInfo attachment = findAttachmentInfo(attachmentId);
1562                    if (attachment == null) {
1563                        // Called before LoadAttachmentsTask finishes.
1564                        // (Possible if you quickly close & re-open a message)
1565                        return;
1566                    }
1567                    attachment.cancelButton.setVisibility(View.GONE);
1568                    attachment.loadButton.setVisibility(View.VISIBLE);
1569                    attachment.progressView.setVisibility(View.INVISIBLE);
1570
1571                    final String error;
1572                    if (result.getCause() instanceof IOException) {
1573                        error = mContext.getString(R.string.status_network_error);
1574                    } else {
1575                        error = mContext.getString(
1576                                R.string.message_view_load_attachment_failed_toast,
1577                                attachment.name);
1578                    }
1579                    mCallback.onLoadMessageError(error);
1580                }
1581            }
1582        }
1583
1584        private void showAttachmentProgress(long attachmentId, int progress) {
1585            AttachmentInfo attachment = findAttachmentInfo(attachmentId);
1586            if (attachment != null) {
1587                ProgressBar bar = attachment.progressView;
1588                if (progress == 0) {
1589                    // When the download starts, we can get rid of the indeterminate bar
1590                    bar.setVisibility(View.VISIBLE);
1591                    bar.setIndeterminate(false);
1592                    // And we're not implementing stop of in-progress downloads
1593                    attachment.cancelButton.setVisibility(View.GONE);
1594                }
1595                bar.setProgress(progress);
1596            }
1597        }
1598    }
1599
1600    /**
1601     * Class to detect update on the current message (e.g. toggle star).  When it gets content
1602     * change notifications, it kicks {@link ReloadMessageTask}.
1603     *
1604     * TODO Use the new Throttle class.
1605     */
1606    private class MessageObserver extends ContentObserver implements Runnable {
1607        private final Throttle mThrottle;
1608        private final ContentResolver mContentResolver;
1609
1610        private boolean mRegistered;
1611
1612        public MessageObserver(Handler handler, Context context) {
1613            super(handler);
1614            mContentResolver = context.getContentResolver();
1615            mThrottle = new Throttle("MessageObserver", this, handler);
1616        }
1617
1618        public void unregister() {
1619            if (!mRegistered) {
1620                return;
1621            }
1622            mThrottle.cancelScheduledCallback();
1623            mContentResolver.unregisterContentObserver(this);
1624            mRegistered = false;
1625        }
1626
1627        public void register(Uri notifyUri) {
1628            unregister();
1629            mContentResolver.registerContentObserver(notifyUri, true, this);
1630            mRegistered = true;
1631        }
1632
1633        @Override
1634        public boolean deliverSelfNotifications() {
1635            return true;
1636        }
1637
1638        @Override
1639        public void onChange(boolean selfChange) {
1640            mThrottle.onEvent();
1641        }
1642
1643        /**
1644         * This method is delay-called by {@link Throttle} on the UI thread.  Need to make
1645         * sure if the fragment is still valid.  (i.e. don't reload if clearContent() has been
1646         * called.)
1647         */
1648        @Override
1649        public void run() {
1650            if (!isMessageSpecified()) {
1651                return;
1652            }
1653            Utility.cancelTaskInterrupt(mReloadMessageTask);
1654            mReloadMessageTask = new ReloadMessageTask();
1655            mReloadMessageTask.execute();
1656        }
1657    }
1658
1659    public boolean isMessageLoadedForTest() {
1660        return mIsMessageLoadedForTest;
1661    }
1662
1663    public void clearIsMessageLoadedForTest() {
1664        mIsMessageLoadedForTest = true;
1665    }
1666}
1667