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