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