MessageViewFragmentBase.java revision 22d1a794cd9636634bb31689f53603c0ae64c522
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 android.app.Activity;
20import android.app.DownloadManager;
21import android.app.Fragment;
22import android.app.LoaderManager.LoaderCallbacks;
23import android.content.ActivityNotFoundException;
24import android.content.ContentResolver;
25import android.content.ContentUris;
26import android.content.Context;
27import android.content.Intent;
28import android.content.Loader;
29import android.content.pm.PackageManager;
30import android.content.res.Resources;
31import android.database.ContentObserver;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.media.MediaScannerConnection;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.Environment;
38import android.os.Handler;
39import android.provider.ContactsContract;
40import android.provider.ContactsContract.QuickContact;
41import android.text.SpannableStringBuilder;
42import android.text.TextUtils;
43import android.text.format.DateUtils;
44import android.util.Log;
45import android.util.Patterns;
46import android.view.LayoutInflater;
47import android.view.View;
48import android.view.ViewGroup;
49import android.webkit.WebSettings;
50import android.webkit.WebView;
51import android.webkit.WebViewClient;
52import android.widget.Button;
53import android.widget.ImageView;
54import android.widget.LinearLayout;
55import android.widget.ProgressBar;
56import android.widget.TextView;
57
58import com.android.email.AttachmentInfo;
59import com.android.email.Controller;
60import com.android.email.ControllerResultUiThreadWrapper;
61import com.android.email.Email;
62import com.android.email.Preferences;
63import com.android.email.R;
64import com.android.email.Throttle;
65import com.android.email.mail.internet.EmailHtmlUtil;
66import com.android.email.service.AttachmentDownloadService;
67import com.android.emailcommon.Logging;
68import com.android.emailcommon.mail.Address;
69import com.android.emailcommon.mail.MessagingException;
70import com.android.emailcommon.provider.Account;
71import com.android.emailcommon.provider.EmailContent.Attachment;
72import com.android.emailcommon.provider.EmailContent.Body;
73import com.android.emailcommon.provider.EmailContent.Message;
74import com.android.emailcommon.provider.Mailbox;
75import com.android.emailcommon.utility.AttachmentUtilities;
76import com.android.emailcommon.utility.EmailAsyncTask;
77import com.android.emailcommon.utility.Utility;
78import com.google.common.collect.Maps;
79
80import org.apache.commons.io.IOUtils;
81
82import java.io.File;
83import java.io.FileOutputStream;
84import java.io.IOException;
85import java.io.InputStream;
86import java.io.OutputStream;
87import java.util.Formatter;
88import java.util.Map;
89import java.util.regex.Matcher;
90import java.util.regex.Pattern;
91
92// TODO Better handling of config changes.
93// - Retain the content; don't kick 3 async tasks every time
94
95/**
96 * Base class for {@link MessageViewFragment} and {@link MessageFileViewFragment}.
97 */
98public abstract class MessageViewFragmentBase extends Fragment implements View.OnClickListener {
99    private static final String BUNDLE_KEY_CURRENT_TAB = "MessageViewFragmentBase.currentTab";
100    private static final String BUNDLE_KEY_PICTURE_LOADED = "MessageViewFragmentBase.pictureLoaded";
101    private static final int PHOTO_LOADER_ID = 1;
102    protected Context mContext;
103
104    // Regex that matches start of img tag. '<(?i)img\s+'.
105    private static final Pattern IMG_TAG_START_REGEX = Pattern.compile("<(?i)img\\s+");
106    // Regex that matches Web URL protocol part as case insensitive.
107    private static final Pattern WEB_URL_PROTOCOL = Pattern.compile("(?i)http|https://");
108
109    private static int PREVIEW_ICON_WIDTH = 62;
110    private static int PREVIEW_ICON_HEIGHT = 62;
111
112    private TextView mSubjectView;
113    private TextView mFromNameView;
114    private TextView mFromAddressView;
115    private TextView mDateTimeView;
116    private TextView mAddressesView;
117    private WebView mMessageContentView;
118    private LinearLayout mAttachments;
119    private View mTabSection;
120    private ImageView mFromBadge;
121    private ImageView mSenderPresenceView;
122    private View mMainView;
123    private View mLoadingProgress;
124    private View mDetailsCollapsed;
125    private View mDetailsExpanded;
126    private boolean mDetailsFilled;
127
128    private TextView mMessageTab;
129    private TextView mAttachmentTab;
130    private TextView mInviteTab;
131    // It is not really a tab, but looks like one of them.
132    private TextView mShowPicturesTab;
133    private ViewGroup mAlwaysShowPicturesContainer;
134    private Button mAlwaysShowPicturesButton;
135
136    private View mAttachmentsScroll;
137    private View mInviteScroll;
138
139    private long mAccountId = Account.NO_ACCOUNT;
140    private long mMessageId = Message.NO_MESSAGE;
141    private Message mMessage;
142
143    private Controller mController;
144    private ControllerResultUiThreadWrapper<ControllerResults> mControllerCallback;
145
146    // contains the HTML body. Is used by LoadAttachmentTask to display inline images.
147    // is null most of the time, is used transiently to pass info to LoadAttachementTask
148    private String mHtmlTextRaw;
149
150    // contains the HTML content as set in WebView.
151    private String mHtmlTextWebView;
152
153    private boolean mIsMessageLoadedForTest;
154
155    private MessageObserver mMessageObserver;
156
157    private static final int CONTACT_STATUS_STATE_UNLOADED = 0;
158    private static final int CONTACT_STATUS_STATE_UNLOADED_TRIGGERED = 1;
159    private static final int CONTACT_STATUS_STATE_LOADED = 2;
160
161    private int mContactStatusState;
162    private Uri mQuickContactLookupUri;
163
164    /** Flag for {@link #mTabFlags}: Message has attachment(s) */
165    protected static final int TAB_FLAGS_HAS_ATTACHMENT = 1;
166
167    /**
168     * Flag for {@link #mTabFlags}: Message contains invite.  This flag is only set by
169     * {@link MessageViewFragment}.
170     */
171    protected static final int TAB_FLAGS_HAS_INVITE = 2;
172
173    /** Flag for {@link #mTabFlags}: Message contains pictures */
174    protected static final int TAB_FLAGS_HAS_PICTURES = 4;
175
176    /** Flag for {@link #mTabFlags}: "Show pictures" has already been pressed */
177    protected static final int TAB_FLAGS_PICTURE_LOADED = 8;
178
179    /**
180     * Flags to control the tabs.
181     * @see #updateTabs(int)
182     */
183    private int mTabFlags;
184
185    /** # of attachments in the current message */
186    private int mAttachmentCount;
187
188    // Use (random) large values, to avoid confusion with TAB_FLAGS_*
189    protected static final int TAB_MESSAGE = 101;
190    protected static final int TAB_INVITE = 102;
191    protected static final int TAB_ATTACHMENT = 103;
192    private static final int TAB_NONE = 0;
193
194    /** Current tab */
195    private int mCurrentTab = TAB_NONE;
196    /**
197     * Tab that was selected in the previous activity instance.
198     * Used to restore the current tab after screen rotation.
199     */
200    private int mRestoredTab = TAB_NONE;
201
202    private boolean mRestoredPictureLoaded;
203
204    private final EmailAsyncTask.Tracker mTaskTracker = new EmailAsyncTask.Tracker();
205
206    /**
207     * Zoom scales for webview.  Values correspond to {@link Preferences#TEXT_ZOOM_TINY}..
208     * {@link Preferences#TEXT_ZOOM_HUGE}.
209     */
210    private static final float[] ZOOM_SCALE_ARRAY = new float[] {0.8f, 0.9f, 1.0f, 1.2f, 1.5f};
211
212    public interface Callback {
213        /**
214         * Called when a link in a message is clicked.
215         *
216         * @param url link url that's clicked.
217         * @return true if handled, false otherwise.
218         */
219        public boolean onUrlInMessageClicked(String url);
220
221        /**
222         * Called when the message specified doesn't exist, or is deleted/moved.
223         */
224        public void onMessageNotExists();
225
226        /** Called when it starts loading a message. */
227        public void onLoadMessageStarted();
228
229        /** Called when it successfully finishes loading a message. */
230        public void onLoadMessageFinished();
231
232        /** Called when an error occurred during loading a message. */
233        public void onLoadMessageError(String errorMessage);
234    }
235
236    public static class EmptyCallback implements Callback {
237        public static final Callback INSTANCE = new EmptyCallback();
238        @Override public void onLoadMessageError(String errorMessage) {}
239        @Override public void onLoadMessageFinished() {}
240        @Override public void onLoadMessageStarted() {}
241        @Override public void onMessageNotExists() {}
242        @Override
243        public boolean onUrlInMessageClicked(String url) {
244            return false;
245        }
246    }
247
248    private Callback mCallback = EmptyCallback.INSTANCE;
249
250    @Override
251    public void onAttach(Activity activity) {
252        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
253            Log.d(Logging.LOG_TAG, this + " onAttach");
254        }
255        super.onAttach(activity);
256    }
257
258    @Override
259    public void onCreate(Bundle savedInstanceState) {
260        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
261            Log.d(Logging.LOG_TAG, this + " onCreate");
262        }
263        super.onCreate(savedInstanceState);
264
265        mContext = getActivity().getApplicationContext();
266
267        // Initialize components, but don't "start" them.  Registering the controller callbacks
268        // and starting MessageObserver, should be done in onActivityCreated or later and be stopped
269        // in onDestroyView to prevent from getting callbacks when the fragment is in the back
270        // stack, but they'll start again when it's back from the back stack.
271        mController = Controller.getInstance(mContext);
272        mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
273                new Handler(), new ControllerResults());
274        mMessageObserver = new MessageObserver(new Handler(), mContext);
275
276        if (savedInstanceState != null) {
277            restoreInstanceState(savedInstanceState);
278        }
279    }
280
281    @Override
282    public View onCreateView(
283            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
284        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
285            Log.d(Logging.LOG_TAG, this + " onCreateView");
286        }
287        final View view = inflater.inflate(R.layout.message_view_fragment, container, false);
288
289        cleanupDetachedViews();
290
291        mSubjectView = (TextView) UiUtilities.getView(view, R.id.subject);
292        mFromNameView = (TextView) UiUtilities.getView(view, R.id.from_name);
293        mFromAddressView = (TextView) UiUtilities.getView(view, R.id.from_address);
294        mAddressesView = (TextView) UiUtilities.getView(view, R.id.addresses);
295        mDateTimeView = (TextView) UiUtilities.getView(view, R.id.datetime);
296        mMessageContentView = (WebView) UiUtilities.getView(view, R.id.message_content);
297        mAttachments = (LinearLayout) UiUtilities.getView(view, R.id.attachments);
298        mTabSection = UiUtilities.getView(view, R.id.message_tabs_section);
299        mFromBadge = (ImageView) UiUtilities.getView(view, R.id.badge);
300        mSenderPresenceView = (ImageView) UiUtilities.getView(view, R.id.presence);
301        mMainView = UiUtilities.getView(view, R.id.main_panel);
302        mLoadingProgress = UiUtilities.getView(view, R.id.loading_progress);
303        mDetailsCollapsed = UiUtilities.getView(view, R.id.sub_header_contents_collapsed);
304        mDetailsExpanded = UiUtilities.getView(view, R.id.sub_header_contents_expanded);
305
306        mFromNameView.setOnClickListener(this);
307        mFromAddressView.setOnClickListener(this);
308        mFromBadge.setOnClickListener(this);
309        mSenderPresenceView.setOnClickListener(this);
310
311        mMessageTab = UiUtilities.getView(view, R.id.show_message);
312        mAttachmentTab = UiUtilities.getView(view, R.id.show_attachments);
313        mShowPicturesTab = UiUtilities.getView(view, R.id.show_pictures);
314        mAlwaysShowPicturesButton = UiUtilities.getView(view, R.id.always_show_pictures_button);
315        mAlwaysShowPicturesContainer = UiUtilities.getView(
316                view, R.id.always_show_pictures_container);
317        // Invite is only used in MessageViewFragment, but visibility is controlled here.
318        mInviteTab = UiUtilities.getView(view, R.id.show_invite);
319
320        mMessageTab.setOnClickListener(this);
321        mAttachmentTab.setOnClickListener(this);
322        mShowPicturesTab.setOnClickListener(this);
323        mAlwaysShowPicturesButton.setOnClickListener(this);
324        mInviteTab.setOnClickListener(this);
325        mDetailsCollapsed.setOnClickListener(this);
326        mDetailsExpanded.setOnClickListener(this);
327
328        mAttachmentsScroll = UiUtilities.getView(view, R.id.attachments_scroll);
329        mInviteScroll = UiUtilities.getView(view, R.id.invite_scroll);
330
331        WebSettings webSettings = mMessageContentView.getSettings();
332        boolean supportMultiTouch = mContext.getPackageManager()
333                .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
334        webSettings.setDisplayZoomControls(!supportMultiTouch);
335        webSettings.setSupportZoom(true);
336        webSettings.setBuiltInZoomControls(true);
337        mMessageContentView.setWebViewClient(new CustomWebViewClient());
338        return view;
339    }
340
341    @Override
342    public void onActivityCreated(Bundle savedInstanceState) {
343        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
344            Log.d(Logging.LOG_TAG, this + " onActivityCreated");
345        }
346        super.onActivityCreated(savedInstanceState);
347        mController.addResultCallback(mControllerCallback);
348
349        resetView();
350        new LoadMessageTask(true).executeParallel();
351
352        UiUtilities.installFragment(this);
353    }
354
355    @Override
356    public void onStart() {
357        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
358            Log.d(Logging.LOG_TAG, this + " onStart");
359        }
360        super.onStart();
361    }
362
363    @Override
364    public void onResume() {
365        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
366            Log.d(Logging.LOG_TAG, this + " onResume");
367        }
368        super.onResume();
369
370        // We might have comes back from other full-screen activities.  If so, we need to update
371        // the attachment tab as system settings may have been updated that affect which
372        // options are available to the user.
373        updateAttachmentTab();
374    }
375
376    @Override
377    public void onPause() {
378        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
379            Log.d(Logging.LOG_TAG, this + " onPause");
380        }
381        super.onPause();
382    }
383
384    @Override
385    public void onStop() {
386        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
387            Log.d(Logging.LOG_TAG, this + " onStop");
388        }
389        super.onStop();
390    }
391
392    @Override
393    public void onDestroyView() {
394        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
395            Log.d(Logging.LOG_TAG, this + " onDestroyView");
396        }
397        UiUtilities.uninstallFragment(this);
398        mController.removeResultCallback(mControllerCallback);
399        cancelAllTasks();
400
401        // We should clean up the Webview here, but it can't release resources until it is
402        // actually removed from the view tree.
403
404        super.onDestroyView();
405    }
406
407    private void cleanupDetachedViews() {
408        // WebView cleanup must be done after it leaves the rendering tree, according to
409        // its contract
410        if (mMessageContentView != null) {
411            mMessageContentView.destroy();
412            mMessageContentView = null;
413        }
414    }
415
416    @Override
417    public void onDestroy() {
418        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
419            Log.d(Logging.LOG_TAG, this + " onDestroy");
420        }
421
422        cleanupDetachedViews();
423        super.onDestroy();
424    }
425
426    @Override
427    public void onDetach() {
428        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
429            Log.d(Logging.LOG_TAG, this + " onDetach");
430        }
431        super.onDetach();
432    }
433
434    @Override
435    public void onSaveInstanceState(Bundle outState) {
436        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
437            Log.d(Logging.LOG_TAG, this + " onSaveInstanceState");
438        }
439        super.onSaveInstanceState(outState);
440        outState.putInt(BUNDLE_KEY_CURRENT_TAB, mCurrentTab);
441        outState.putBoolean(BUNDLE_KEY_PICTURE_LOADED, (mTabFlags & TAB_FLAGS_PICTURE_LOADED) != 0);
442    }
443
444    private void restoreInstanceState(Bundle state) {
445        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
446            Log.d(Logging.LOG_TAG, this + " restoreInstanceState");
447        }
448        // At this point (in onCreate) no tabs are visible (because we don't know if the message has
449        // an attachment or invite before loading it).  We just remember the tab here.
450        // We'll make it current when the tab first becomes visible in updateTabs().
451        mRestoredTab = state.getInt(BUNDLE_KEY_CURRENT_TAB);
452        mRestoredPictureLoaded = state.getBoolean(BUNDLE_KEY_PICTURE_LOADED);
453    }
454
455    public void setCallback(Callback callback) {
456        mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback;
457    }
458
459    private void cancelAllTasks() {
460        mMessageObserver.unregister();
461        mTaskTracker.cancellAllInterrupt();
462    }
463
464    protected final Controller getController() {
465        return mController;
466    }
467
468    protected final Callback getCallback() {
469        return mCallback;
470    }
471
472    protected final Message getMessage() {
473        return mMessage;
474    }
475
476    protected final boolean isMessageOpen() {
477        return mMessage != null;
478    }
479
480    /**
481     * Returns the account id of the current message, or -1 if unknown (message not open yet, or
482     * viewing an EML message).
483     */
484    public long getAccountId() {
485        return mAccountId;
486    }
487
488    /**
489     * Show/hide the content.  We hide all the content (except for the bottom buttons) when loading,
490     * to avoid flicker.
491     */
492    private void showContent(boolean showContent, boolean showProgressWhenHidden) {
493        makeVisible(mMainView, showContent);
494        makeVisible(mLoadingProgress, !showContent && showProgressWhenHidden);
495    }
496
497    protected void resetView() {
498        showContent(false, false);
499        updateTabs(0);
500        setCurrentTab(TAB_MESSAGE);
501        if (mMessageContentView != null) {
502            blockNetworkLoads(true);
503            mMessageContentView.scrollTo(0, 0);
504            mMessageContentView.clearView();
505
506            // Dynamic configuration of WebView
507            final WebSettings settings = mMessageContentView.getSettings();
508            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
509            mMessageContentView.setInitialScale(getWebViewZoom());
510        }
511        mAttachmentsScroll.scrollTo(0, 0);
512        mInviteScroll.scrollTo(0, 0);
513        mAttachments.removeAllViews();
514        mAttachments.setVisibility(View.GONE);
515        initContactStatusViews();
516    }
517
518    /**
519     * Returns the zoom scale (in percent) which is a combination of the user setting
520     * (tiny, small, normal, large, huge) and the device density. The intention
521     * is for the text to be physically equal in size over different density
522     * screens.
523     */
524    private int getWebViewZoom() {
525        float density = mContext.getResources().getDisplayMetrics().density;
526        int zoom = Preferences.getPreferences(mContext).getTextZoom();
527        return (int) (ZOOM_SCALE_ARRAY[zoom] * density * 100);
528    }
529
530    private void initContactStatusViews() {
531        mContactStatusState = CONTACT_STATUS_STATE_UNLOADED;
532        mQuickContactLookupUri = null;
533        mSenderPresenceView.setImageResource(ContactStatusLoader.PRESENCE_UNKNOWN_RESOURCE_ID);
534        showDefaultQuickContactBadgeImage();
535    }
536
537    private void showDefaultQuickContactBadgeImage() {
538        mFromBadge.setImageResource(R.drawable.ic_contact_picture);
539    }
540
541    protected final void addTabFlags(int tabFlags) {
542        updateTabs(mTabFlags | tabFlags);
543    }
544
545    private final void clearTabFlags(int tabFlags) {
546        updateTabs(mTabFlags & ~tabFlags);
547    }
548
549    private void setAttachmentCount(int count) {
550        mAttachmentCount = count;
551        if (mAttachmentCount > 0) {
552            addTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
553        } else {
554            clearTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
555        }
556    }
557
558    private static void makeVisible(View v, boolean visible) {
559        final int visibility = visible ? View.VISIBLE : View.GONE;
560        if ((v != null) && (v.getVisibility() != visibility)) {
561            v.setVisibility(visibility);
562        }
563    }
564
565    private static boolean isVisible(View v) {
566        return (v != null) && (v.getVisibility() == View.VISIBLE);
567    }
568
569    /**
570     * Update the visual of the tabs.  (visibility, text, etc)
571     */
572    private void updateTabs(int tabFlags) {
573        mTabFlags = tabFlags;
574
575        if (getView() == null) {
576            return;
577        }
578
579        boolean messageTabVisible = (tabFlags & (TAB_FLAGS_HAS_INVITE | TAB_FLAGS_HAS_ATTACHMENT))
580                != 0;
581        makeVisible(mMessageTab, messageTabVisible);
582        makeVisible(mInviteTab, (tabFlags & TAB_FLAGS_HAS_INVITE) != 0);
583        makeVisible(mAttachmentTab, (tabFlags & TAB_FLAGS_HAS_ATTACHMENT) != 0);
584
585        final boolean hasPictures = (tabFlags & TAB_FLAGS_HAS_PICTURES) != 0;
586        final boolean pictureLoaded = (tabFlags & TAB_FLAGS_PICTURE_LOADED) != 0;
587        makeVisible(mShowPicturesTab, hasPictures && !pictureLoaded);
588
589        mAttachmentTab.setText(mContext.getResources().getQuantityString(
590                R.plurals.message_view_show_attachments_action,
591                mAttachmentCount, mAttachmentCount));
592
593        // Hide the entire section if no tabs are visible.
594        makeVisible(mTabSection, isVisible(mMessageTab) || isVisible(mInviteTab)
595                || isVisible(mAttachmentTab) || isVisible(mShowPicturesTab)
596                || isVisible(mAlwaysShowPicturesContainer));
597
598        // Restore previously selected tab after rotation
599        if (mRestoredTab != TAB_NONE && isVisible(getTabViewForFlag(mRestoredTab))) {
600            setCurrentTab(mRestoredTab);
601            mRestoredTab = TAB_NONE;
602        }
603    }
604
605    /**
606     * Set the current tab.
607     *
608     * @param tab any of {@link #TAB_MESSAGE}, {@link #TAB_ATTACHMENT} or {@link #TAB_INVITE}.
609     */
610    private void setCurrentTab(int tab) {
611        mCurrentTab = tab;
612
613        // Hide & unselect all tabs
614        makeVisible(getTabContentViewForFlag(TAB_MESSAGE), false);
615        makeVisible(getTabContentViewForFlag(TAB_ATTACHMENT), false);
616        makeVisible(getTabContentViewForFlag(TAB_INVITE), false);
617        getTabViewForFlag(TAB_MESSAGE).setSelected(false);
618        getTabViewForFlag(TAB_ATTACHMENT).setSelected(false);
619        getTabViewForFlag(TAB_INVITE).setSelected(false);
620
621        makeVisible(getTabContentViewForFlag(mCurrentTab), true);
622        getTabViewForFlag(mCurrentTab).setSelected(true);
623    }
624
625    private View getTabViewForFlag(int tabFlag) {
626        switch (tabFlag) {
627            case TAB_MESSAGE:
628                return mMessageTab;
629            case TAB_ATTACHMENT:
630                return mAttachmentTab;
631            case TAB_INVITE:
632                return mInviteTab;
633        }
634        throw new IllegalArgumentException();
635    }
636
637    private View getTabContentViewForFlag(int tabFlag) {
638        switch (tabFlag) {
639            case TAB_MESSAGE:
640                return mMessageContentView;
641            case TAB_ATTACHMENT:
642                return mAttachmentsScroll;
643            case TAB_INVITE:
644                return mInviteScroll;
645        }
646        throw new IllegalArgumentException();
647    }
648
649    private void blockNetworkLoads(boolean block) {
650        if (mMessageContentView != null) {
651            mMessageContentView.getSettings().setBlockNetworkLoads(block);
652        }
653    }
654
655    private void setMessageHtml(String html) {
656        if (html == null) {
657            html = "";
658        }
659        if (mMessageContentView != null) {
660            mMessageContentView.loadDataWithBaseURL("email://", html, "text/html", "utf-8", null);
661        }
662    }
663
664    /**
665     * Handle clicks on sender, which shows {@link QuickContact} or prompts to add
666     * the sender as a contact.
667     */
668    private void onClickSender() {
669        if (!isMessageOpen()) return;
670        final Address senderEmail = Address.unpackFirst(mMessage.mFrom);
671        if (senderEmail == null) return;
672
673        if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED) {
674            // Status not loaded yet.
675            mContactStatusState = CONTACT_STATUS_STATE_UNLOADED_TRIGGERED;
676            return;
677        }
678        if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED) {
679            return; // Already clicked, and waiting for the data.
680        }
681
682        if (mQuickContactLookupUri != null) {
683            QuickContact.showQuickContact(mContext, mFromBadge, mQuickContactLookupUri,
684                        QuickContact.MODE_LARGE, null);
685        } else {
686            // No matching contact, ask user to create one
687            final Uri mailUri = Uri.fromParts("mailto", senderEmail.getAddress(), null);
688            final Intent intent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT,
689                    mailUri);
690
691            // Pass along full E-mail string for possible create dialog
692            intent.putExtra(ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION,
693                    senderEmail.toString());
694
695            // Only provide personal name hint if we have one
696            final String senderPersonal = senderEmail.getPersonal();
697            if (!TextUtils.isEmpty(senderPersonal)) {
698                intent.putExtra(ContactsContract.Intents.Insert.NAME, senderPersonal);
699            }
700            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
701
702            startActivity(intent);
703        }
704    }
705
706    private static class ContactStatusLoaderCallbacks
707            implements LoaderCallbacks<ContactStatusLoader.Result> {
708        private static final String BUNDLE_EMAIL_ADDRESS = "email";
709        private final MessageViewFragmentBase mFragment;
710
711        public ContactStatusLoaderCallbacks(MessageViewFragmentBase fragment) {
712            mFragment = fragment;
713        }
714
715        public static Bundle createArguments(String emailAddress) {
716            Bundle b = new Bundle();
717            b.putString(BUNDLE_EMAIL_ADDRESS, emailAddress);
718            return b;
719        }
720
721        @Override
722        public Loader<ContactStatusLoader.Result> onCreateLoader(int id, Bundle args) {
723            return new ContactStatusLoader(mFragment.mContext,
724                    args.getString(BUNDLE_EMAIL_ADDRESS));
725        }
726
727        @Override
728        public void onLoadFinished(Loader<ContactStatusLoader.Result> loader,
729                ContactStatusLoader.Result result) {
730            boolean triggered =
731                    (mFragment.mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED);
732            mFragment.mContactStatusState = CONTACT_STATUS_STATE_LOADED;
733            mFragment.mQuickContactLookupUri = result.mLookupUri;
734            mFragment.mSenderPresenceView.setImageResource(result.mPresenceResId);
735            if (result.mPhoto != null) { // photo will be null if unknown.
736                mFragment.mFromBadge.setImageBitmap(result.mPhoto);
737            }
738            if (triggered) {
739                mFragment.onClickSender();
740            }
741        }
742
743        @Override
744        public void onLoaderReset(Loader<ContactStatusLoader.Result> loader) {
745        }
746    }
747
748    private void onSaveAttachment(MessageViewAttachmentInfo info) {
749        if (!Utility.isExternalStorageMounted()) {
750            /*
751             * Abort early if there's no place to save the attachment. We don't want to spend
752             * the time downloading it and then abort.
753             */
754            Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
755            return;
756        }
757
758        if (info.isFileSaved()) {
759            // Nothing to do - we have the file saved.
760            return;
761        }
762
763        File savedFile = performAttachmentSave(info);
764        if (savedFile != null) {
765            Utility.showToast(getActivity(), String.format(
766                    mContext.getString(R.string.message_view_status_attachment_saved),
767                    savedFile.getName()));
768        } else {
769            Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
770        }
771    }
772
773    private File performAttachmentSave(MessageViewAttachmentInfo info) {
774        Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.mId);
775        Uri attachmentUri = AttachmentUtilities.getAttachmentUri(mAccountId, attachment.mId);
776
777        try {
778            File downloads = Environment.getExternalStoragePublicDirectory(
779                    Environment.DIRECTORY_DOWNLOADS);
780            downloads.mkdirs();
781            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
782            Uri contentUri = AttachmentUtilities.resolveAttachmentIdToContentUri(
783                    mContext.getContentResolver(), attachmentUri);
784            InputStream in = mContext.getContentResolver().openInputStream(contentUri);
785            OutputStream out = new FileOutputStream(file);
786            IOUtils.copy(in, out);
787            out.flush();
788            out.close();
789            in.close();
790
791            String absolutePath = file.getAbsolutePath();
792
793            // Although the download manager can scan media files, scanning only happens after the
794            // user clicks on the item in the Downloads app. So, we run the attachment through
795            // the media scanner ourselves so it gets added to gallery / music immediately.
796            MediaScannerConnection.scanFile(mContext, new String[] {absolutePath},
797                    null, null);
798
799            DownloadManager dm =
800                    (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
801            dm.addCompletedDownload(info.mName, info.mName,
802                    false /* do not use media scanner */,
803                    info.mContentType, absolutePath, info.mSize,
804                    true /* show notification */);
805
806            // Cache the stored file information.
807            info.setSavedPath(absolutePath);
808
809            // Update our buttons.
810            updateAttachmentButtons(info);
811
812            return file;
813
814        } catch (IOException ioe) {
815            // Ignore. Callers will handle it from the return code.
816        }
817
818        return null;
819    }
820
821    private void onOpenAttachment(MessageViewAttachmentInfo info) {
822        if (info.mAllowInstall) {
823            // The package installer is unable to install files from a content URI; it must be
824            // given a file path. Therefore, we need to save it first in order to proceed
825            if (!info.mAllowSave || !Utility.isExternalStorageMounted()) {
826                Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
827                return;
828            }
829
830            if (!info.isFileSaved()) {
831                if (performAttachmentSave(info) == null) {
832                    // Saving failed for some reason - bail.
833                    Utility.showToast(
834                            getActivity(), R.string.message_view_status_attachment_not_saved);
835                    return;
836                }
837            }
838        }
839        try {
840            Intent intent = info.getAttachmentIntent(mContext, mAccountId);
841            startActivity(intent);
842        } catch (ActivityNotFoundException e) {
843            Utility.showToast(getActivity(), R.string.message_view_display_attachment_toast);
844        }
845    }
846
847    private void onInfoAttachment(final MessageViewAttachmentInfo attachment) {
848        AttachmentInfoDialog dialog =
849            AttachmentInfoDialog.newInstance(getActivity(), attachment.mDenyFlags);
850        dialog.show(getActivity().getFragmentManager(), null);
851    }
852
853    private void onLoadAttachment(final MessageViewAttachmentInfo attachment) {
854        attachment.loadButton.setVisibility(View.GONE);
855        // If there's nothing in the download queue, we'll probably start right away so wait a
856        // second before showing the cancel button
857        if (AttachmentDownloadService.getQueueSize() == 0) {
858            // Set to invisible; if the button is still in this state one second from now, we'll
859            // assume the download won't start right away, and we make the cancel button visible
860            attachment.cancelButton.setVisibility(View.GONE);
861            // Create the timed task that will change the button state
862            new EmailAsyncTask<Void, Void, Void>(mTaskTracker) {
863                @Override
864                protected Void doInBackground(Void... params) {
865                    try {
866                        Thread.sleep(1000L);
867                    } catch (InterruptedException e) { }
868                    return null;
869                }
870                @Override
871                protected void onSuccess(Void result) {
872                    // If the timeout completes and the attachment has not loaded, show cancel
873                    if (!attachment.loaded) {
874                        attachment.cancelButton.setVisibility(View.VISIBLE);
875                    }
876                }
877            }.executeParallel();
878        } else {
879            attachment.cancelButton.setVisibility(View.VISIBLE);
880        }
881        attachment.showProgressIndeterminate();
882        mController.loadAttachment(attachment.mId, mMessageId, mAccountId);
883    }
884
885    private void onCancelAttachment(MessageViewAttachmentInfo attachment) {
886        // Don't change button states if we couldn't cancel the download
887        if (AttachmentDownloadService.cancelQueuedAttachment(attachment.mId)) {
888            attachment.loadButton.setVisibility(View.VISIBLE);
889            attachment.cancelButton.setVisibility(View.GONE);
890            attachment.hideProgress();
891        }
892    }
893
894    /**
895     * Called by ControllerResults. Show the "View" and "Save" buttons; hide "Load" and "Stop"
896     *
897     * @param attachmentId the attachment that was just downloaded
898     */
899    private void doFinishLoadAttachment(long attachmentId) {
900        MessageViewAttachmentInfo info = findAttachmentInfo(attachmentId);
901        if (info != null) {
902            info.loaded = true;
903            updateAttachmentButtons(info);
904        }
905    }
906
907    private void showPicturesInHtml() {
908        boolean picturesAlreadyLoaded = (mTabFlags & TAB_FLAGS_PICTURE_LOADED) != 0;
909        if ((mMessageContentView != null) && !picturesAlreadyLoaded) {
910            blockNetworkLoads(false);
911            // TODO: why is this calling setMessageHtml just because the images can load now?
912            setMessageHtml(mHtmlTextWebView);
913
914            // Prompt the user to always show images from this sender.
915            makeVisible(UiUtilities.getView(getView(), R.id.always_show_pictures_container), true);
916
917            addTabFlags(TAB_FLAGS_PICTURE_LOADED);
918        }
919    }
920
921    private void showDetails() {
922        if (!isMessageOpen()) {
923            return;
924        }
925
926        if (!mDetailsFilled) {
927            String date = formatDate(mMessage.mTimeStamp, true);
928            final String SEPARATOR = "\n";
929            String to = Address.toString(Address.unpack(mMessage.mTo), SEPARATOR);
930            String cc = Address.toString(Address.unpack(mMessage.mCc), SEPARATOR);
931            String bcc = Address.toString(Address.unpack(mMessage.mBcc), SEPARATOR);
932            setDetailsRow(mDetailsExpanded, date, R.id.date, R.id.date_row);
933            setDetailsRow(mDetailsExpanded, to, R.id.to, R.id.to_row);
934            setDetailsRow(mDetailsExpanded, cc, R.id.cc, R.id.cc_row);
935            setDetailsRow(mDetailsExpanded, bcc, R.id.bcc, R.id.bcc_row);
936            mDetailsFilled = true;
937        }
938
939        mDetailsCollapsed.setVisibility(View.GONE);
940        mDetailsExpanded.setVisibility(View.VISIBLE);
941    }
942
943    private void hideDetails() {
944        mDetailsCollapsed.setVisibility(View.VISIBLE);
945        mDetailsExpanded.setVisibility(View.GONE);
946    }
947
948    private static void setDetailsRow(View root, String text, int textViewId, int rowViewId) {
949        if (TextUtils.isEmpty(text)) {
950            root.findViewById(rowViewId).setVisibility(View.GONE);
951            return;
952        }
953        ((TextView) UiUtilities.getView(root, textViewId)).setText(text);
954    }
955
956
957    @Override
958    public void onClick(View view) {
959        if (!isMessageOpen()) {
960            return; // Ignore.
961        }
962        switch (view.getId()) {
963            case R.id.from_name:
964            case R.id.from_address:
965            case R.id.badge:
966            case R.id.presence:
967                onClickSender();
968                break;
969            case R.id.load:
970                onLoadAttachment((MessageViewAttachmentInfo) view.getTag());
971                break;
972            case R.id.info:
973                onInfoAttachment((MessageViewAttachmentInfo) view.getTag());
974                break;
975            case R.id.save:
976                onSaveAttachment((MessageViewAttachmentInfo) view.getTag());
977                break;
978            case R.id.open:
979                onOpenAttachment((MessageViewAttachmentInfo) view.getTag());
980                break;
981            case R.id.cancel:
982                onCancelAttachment((MessageViewAttachmentInfo) view.getTag());
983                break;
984            case R.id.show_message:
985                setCurrentTab(TAB_MESSAGE);
986                break;
987            case R.id.show_invite:
988                setCurrentTab(TAB_INVITE);
989                break;
990            case R.id.show_attachments:
991                setCurrentTab(TAB_ATTACHMENT);
992                break;
993            case R.id.show_pictures:
994                showPicturesInHtml();
995                break;
996            case R.id.always_show_pictures_button:
997                setShowImagesForSender();
998                break;
999            case R.id.sub_header_contents_collapsed:
1000                showDetails();
1001                break;
1002            case R.id.sub_header_contents_expanded:
1003                hideDetails();
1004                break;
1005        }
1006    }
1007
1008    /**
1009     * Start loading contact photo and presence.
1010     */
1011    private void queryContactStatus() {
1012        if (!isMessageOpen()) return;
1013        initContactStatusViews(); // Initialize the state, just in case.
1014
1015        // Find the sender email address, and start presence check.
1016        Address sender = Address.unpackFirst(mMessage.mFrom);
1017        if (sender != null) {
1018            String email = sender.getAddress();
1019            if (email != null) {
1020                getLoaderManager().restartLoader(PHOTO_LOADER_ID,
1021                        ContactStatusLoaderCallbacks.createArguments(email),
1022                        new ContactStatusLoaderCallbacks(this));
1023            }
1024        }
1025    }
1026
1027    /**
1028     * Called by {@link LoadMessageTask} and {@link ReloadMessageTask} to load a message in a
1029     * subclass specific way.
1030     *
1031     * NOTE This method is called on a worker thread!  Implementations must properly synchronize
1032     * when accessing members.
1033     *
1034     * @param activity the parent activity.  Subclass use it as a context, and to show a toast.
1035     */
1036    protected abstract Message openMessageSync(Activity activity);
1037
1038    /**
1039     * Async task for loading a single message outside of the UI thread
1040     */
1041    private class LoadMessageTask extends EmailAsyncTask<Void, Void, Message> {
1042
1043        private final boolean mOkToFetch;
1044        private int mMailboxType;
1045
1046        /**
1047         * Special constructor to cache some local info
1048         */
1049        public LoadMessageTask(boolean okToFetch) {
1050            super(mTaskTracker);
1051            mOkToFetch = okToFetch;
1052        }
1053
1054        @Override
1055        protected Message doInBackground(Void... params) {
1056            Activity activity = getActivity();
1057            Message message = null;
1058            if (activity != null) {
1059                message = openMessageSync(activity);
1060            }
1061            if (message != null) {
1062                mMailboxType = Mailbox.getMailboxType(mContext, message.mMailboxKey);
1063                if (mMailboxType == Mailbox.NO_MAILBOX) {
1064                    message = null; // mailbox removed??
1065                }
1066            }
1067            return message;
1068        }
1069
1070        @Override
1071        protected void onSuccess(Message message) {
1072            if (message == null) {
1073                resetView();
1074                mCallback.onMessageNotExists();
1075                return;
1076            }
1077            mMessageId = message.mId;
1078
1079            reloadUiFromMessage(message, mOkToFetch);
1080            queryContactStatus();
1081            onMessageShown(mMessageId, mMailboxType);
1082            RecentMailboxManager.getInstance(mContext).touch(message.mMailboxKey);
1083        }
1084    }
1085
1086    /**
1087     * Kicked by {@link MessageObserver}.  Reload the message and update the views.
1088     */
1089    private class ReloadMessageTask extends EmailAsyncTask<Void, Void, Message> {
1090        public ReloadMessageTask() {
1091            super(mTaskTracker);
1092        }
1093
1094        @Override
1095        protected Message doInBackground(Void... params) {
1096            Activity activity = getActivity();
1097            if (activity == null) {
1098                return null;
1099            } else {
1100                return openMessageSync(activity);
1101            }
1102        }
1103
1104        @Override
1105        protected void onSuccess(Message message) {
1106            if (message == null || message.mMailboxKey != mMessage.mMailboxKey) {
1107                // Message deleted or moved.
1108                mCallback.onMessageNotExists();
1109                return;
1110            }
1111            mMessage = message;
1112            updateHeaderView(mMessage);
1113        }
1114    }
1115
1116    /**
1117     * Called when a message is shown to the user.
1118     */
1119    protected void onMessageShown(long messageId, int mailboxType) {
1120    }
1121
1122    /**
1123     * Called when the message body is loaded.
1124     */
1125    protected void onPostLoadBody() {
1126    }
1127
1128    /**
1129     * Async task for loading a single message body outside of the UI thread
1130     */
1131    private class LoadBodyTask extends EmailAsyncTask<Void, Void, String[]> {
1132
1133        private final long mId;
1134        private boolean mErrorLoadingMessageBody;
1135        private final boolean mAutoShowPictures;
1136
1137        /**
1138         * Special constructor to cache some local info
1139         */
1140        public LoadBodyTask(long messageId, boolean autoShowPictures) {
1141            super(mTaskTracker);
1142            mId = messageId;
1143            mAutoShowPictures = autoShowPictures;
1144        }
1145
1146        @Override
1147        protected String[] doInBackground(Void... params) {
1148            try {
1149                String text = null;
1150                String html = Body.restoreBodyHtmlWithMessageId(mContext, mId);
1151                if (html == null) {
1152                    text = Body.restoreBodyTextWithMessageId(mContext, mId);
1153                }
1154                return new String[] { text, html };
1155            } catch (RuntimeException re) {
1156                // This catches SQLiteException as well as other RTE's we've seen from the
1157                // database calls, such as IllegalStateException
1158                Log.d(Logging.LOG_TAG, "Exception while loading message body", re);
1159                mErrorLoadingMessageBody = true;
1160                return null;
1161            }
1162        }
1163
1164        @Override
1165        protected void onSuccess(String[] results) {
1166            if (results == null) {
1167                if (mErrorLoadingMessageBody) {
1168                    Utility.showToast(getActivity(), R.string.error_loading_message_body);
1169                }
1170                resetView();
1171                return;
1172            }
1173            reloadUiFromBody(results[0], results[1], mAutoShowPictures);    // text, html
1174            onPostLoadBody();
1175        }
1176    }
1177
1178    /**
1179     * Async task for loading attachments
1180     *
1181     * Note:  This really should only be called when the message load is complete - or, we should
1182     * leave open a listener so the attachments can fill in as they are discovered.  In either case,
1183     * this implementation is incomplete, as it will fail to refresh properly if the message is
1184     * partially loaded at this time.
1185     */
1186    private class LoadAttachmentsTask extends EmailAsyncTask<Long, Void, Attachment[]> {
1187        public LoadAttachmentsTask() {
1188            super(mTaskTracker);
1189        }
1190
1191        @Override
1192        protected Attachment[] doInBackground(Long... messageIds) {
1193            return Attachment.restoreAttachmentsWithMessageId(mContext, messageIds[0]);
1194        }
1195
1196        @Override
1197        protected void onSuccess(Attachment[] attachments) {
1198            try {
1199                if (attachments == null) {
1200                    return;
1201                }
1202                boolean htmlChanged = false;
1203                int numDisplayedAttachments = 0;
1204                for (Attachment attachment : attachments) {
1205                    if (mHtmlTextRaw != null && attachment.mContentId != null
1206                            && attachment.mContentUri != null) {
1207                        // for html body, replace CID for inline images
1208                        // Regexp which matches ' src="cid:contentId"'.
1209                        String contentIdRe =
1210                            "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
1211                        String srcContentUri = " src=\"" + attachment.mContentUri + "\"";
1212                        mHtmlTextRaw = mHtmlTextRaw.replaceAll(contentIdRe, srcContentUri);
1213                        htmlChanged = true;
1214                    } else {
1215                        addAttachment(attachment);
1216                        numDisplayedAttachments++;
1217                    }
1218                }
1219                setAttachmentCount(numDisplayedAttachments);
1220                mHtmlTextWebView = mHtmlTextRaw;
1221                mHtmlTextRaw = null;
1222                if (htmlChanged) {
1223                    setMessageHtml(mHtmlTextWebView);
1224                }
1225            } finally {
1226                showContent(true, false);
1227            }
1228        }
1229    }
1230
1231    private static Bitmap getPreviewIcon(Context context, AttachmentInfo attachment) {
1232        try {
1233            return BitmapFactory.decodeStream(
1234                    context.getContentResolver().openInputStream(
1235                            AttachmentUtilities.getAttachmentThumbnailUri(
1236                                    attachment.mAccountKey, attachment.mId,
1237                                    PREVIEW_ICON_WIDTH,
1238                                    PREVIEW_ICON_HEIGHT)));
1239        } catch (Exception e) {
1240            Log.d(Logging.LOG_TAG, "Attachment preview failed with exception " + e.getMessage());
1241            return null;
1242        }
1243    }
1244
1245    /**
1246     * Subclass of AttachmentInfo which includes our views and buttons related to attachment
1247     * handling, as well as our determination of suitability for viewing (based on availability of
1248     * a viewer app) and saving (based upon the presence of external storage)
1249     */
1250    private static class MessageViewAttachmentInfo extends AttachmentInfo {
1251        private Button openButton;
1252        private Button saveButton;
1253        private Button loadButton;
1254        private Button infoButton;
1255        private Button cancelButton;
1256        private ImageView iconView;
1257
1258        private static final Map<AttachmentInfo, String> sSavedFileInfos = Maps.newHashMap();
1259
1260        // Don't touch it directly from the outer class.
1261        private final ProgressBar mProgressView;
1262        private boolean loaded;
1263
1264        private MessageViewAttachmentInfo(Context context, Attachment attachment,
1265                ProgressBar progressView) {
1266            super(context, attachment);
1267            mProgressView = progressView;
1268        }
1269
1270        /**
1271         * Create a new attachment info based upon an existing attachment info. Display
1272         * related fields (such as views and buttons) are copied from old to new.
1273         */
1274        private MessageViewAttachmentInfo(Context context, MessageViewAttachmentInfo oldInfo) {
1275            super(context, oldInfo);
1276            openButton = oldInfo.openButton;
1277            saveButton = oldInfo.saveButton;
1278            loadButton = oldInfo.loadButton;
1279            infoButton = oldInfo.infoButton;
1280            cancelButton = oldInfo.cancelButton;
1281            iconView = oldInfo.iconView;
1282            mProgressView = oldInfo.mProgressView;
1283            loaded = oldInfo.loaded;
1284        }
1285
1286        public void hideProgress() {
1287            // Don't use GONE, which'll break the layout.
1288            if (mProgressView.getVisibility() != View.INVISIBLE) {
1289                mProgressView.setVisibility(View.INVISIBLE);
1290            }
1291        }
1292
1293        public void showProgress(int progress) {
1294            if (mProgressView.getVisibility() != View.VISIBLE) {
1295                mProgressView.setVisibility(View.VISIBLE);
1296            }
1297            if (mProgressView.isIndeterminate()) {
1298                mProgressView.setIndeterminate(false);
1299            }
1300            mProgressView.setProgress(progress);
1301        }
1302
1303        public void showProgressIndeterminate() {
1304            if (mProgressView.getVisibility() != View.VISIBLE) {
1305                mProgressView.setVisibility(View.VISIBLE);
1306            }
1307            if (!mProgressView.isIndeterminate()) {
1308                mProgressView.setIndeterminate(true);
1309            }
1310        }
1311
1312        /**
1313         * Determines whether or not this attachment has a saved file in the external storage. That
1314         * is, the user has at some point clicked "save" for this attachment.
1315         *
1316         * Note: this is an approximation and uses an in-memory cache that can get wiped when the
1317         * process dies, and so is somewhat conservative. Additionally, the user can modify the file
1318         * after saving, and so the file may not be the same (though this is unlikely).
1319         */
1320        public boolean isFileSaved() {
1321            String path = getSavedPath();
1322            if (path == null) {
1323                return false;
1324            }
1325            boolean savedFileExists = new File(path).exists();
1326            if (!savedFileExists) {
1327                // Purge the cache entry.
1328                setSavedPath(null);
1329            }
1330            return savedFileExists;
1331        }
1332
1333        private void setSavedPath(String path) {
1334            if (path == null) {
1335                sSavedFileInfos.remove(this);
1336            } else {
1337                sSavedFileInfos.put(this, path);
1338            }
1339        }
1340
1341        /**
1342         * Returns an absolute file path for the given attachment if it has been saved. If one is
1343         * not found, {@code null} is returned.
1344         *
1345         * Clients are expected to validate that the file at the given path is still valid.
1346         */
1347        private String getSavedPath() {
1348            return sSavedFileInfos.get(this);
1349        }
1350
1351        @Override
1352        protected Uri getUriForIntent(Context context, long accountId) {
1353            // Prefer to act on the saved file for intents.
1354            String path = getSavedPath();
1355            return (path != null)
1356                    ? Uri.parse("file://" + getSavedPath())
1357                    : super.getUriForIntent(context, accountId);
1358        }
1359    }
1360
1361    /**
1362     * Updates all current attachments on the attachment tab.
1363     */
1364    private void updateAttachmentTab() {
1365        for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
1366            View view = mAttachments.getChildAt(i);
1367            MessageViewAttachmentInfo oldInfo = (MessageViewAttachmentInfo)view.getTag();
1368            MessageViewAttachmentInfo newInfo =
1369                    new MessageViewAttachmentInfo(getActivity(), oldInfo);
1370            updateAttachmentButtons(newInfo);
1371            view.setTag(newInfo);
1372        }
1373    }
1374
1375    /**
1376     * Updates the attachment buttons. Adjusts the visibility of the buttons as well
1377     * as updating any tag information associated with the buttons.
1378     */
1379    private void updateAttachmentButtons(MessageViewAttachmentInfo attachmentInfo) {
1380        ImageView attachmentIcon = attachmentInfo.iconView;
1381        Button openButton = attachmentInfo.openButton;
1382        Button saveButton = attachmentInfo.saveButton;
1383        Button loadButton = attachmentInfo.loadButton;
1384        Button infoButton = attachmentInfo.infoButton;
1385        Button cancelButton = attachmentInfo.cancelButton;
1386
1387        if (!attachmentInfo.mAllowView) {
1388            openButton.setVisibility(View.GONE);
1389        }
1390        if (!attachmentInfo.mAllowSave) {
1391            saveButton.setVisibility(View.GONE);
1392        }
1393
1394        if (!attachmentInfo.mAllowView && !attachmentInfo.mAllowSave) {
1395            // This attachment may never be viewed or saved, so block everything
1396            attachmentInfo.hideProgress();
1397            openButton.setVisibility(View.GONE);
1398            saveButton.setVisibility(View.GONE);
1399            loadButton.setVisibility(View.GONE);
1400            cancelButton.setVisibility(View.GONE);
1401            infoButton.setVisibility(View.VISIBLE);
1402        } else if (attachmentInfo.loaded) {
1403            // If the attachment is loaded, show 100% progress
1404            // Note that for POP3 messages, the user will only see "Open" and "Save",
1405            // because the entire message is loaded before being shown.
1406            // Hide "Load" and "Info", show "View" and "Save"
1407            attachmentInfo.showProgress(100);
1408            if (attachmentInfo.mAllowSave) {
1409                saveButton.setVisibility(View.VISIBLE);
1410
1411                boolean isFileSaved = attachmentInfo.isFileSaved();
1412                saveButton.setEnabled(!isFileSaved);
1413                if (!isFileSaved) {
1414                    saveButton.setText(R.string.message_view_attachment_save_action);
1415                } else {
1416                    saveButton.setText(R.string.message_view_attachment_saved);
1417                }
1418            }
1419            if (attachmentInfo.mAllowView) {
1420                // Set the attachment action button text accordingly
1421                if (attachmentInfo.mContentType.startsWith("audio/") ||
1422                        attachmentInfo.mContentType.startsWith("video/")) {
1423                    openButton.setText(R.string.message_view_attachment_play_action);
1424                } else if (attachmentInfo.mAllowInstall) {
1425                    openButton.setText(R.string.message_view_attachment_install_action);
1426                } else {
1427                    openButton.setText(R.string.message_view_attachment_view_action);
1428                }
1429                openButton.setVisibility(View.VISIBLE);
1430            }
1431            if (attachmentInfo.mDenyFlags == AttachmentInfo.ALLOW) {
1432                infoButton.setVisibility(View.GONE);
1433            } else {
1434                infoButton.setVisibility(View.VISIBLE);
1435            }
1436            loadButton.setVisibility(View.GONE);
1437            cancelButton.setVisibility(View.GONE);
1438
1439            updatePreviewIcon(attachmentInfo);
1440        } else {
1441            // The attachment is not loaded, so present UI to start downloading it
1442
1443            // Show "Load"; hide "View", "Save" and "Info"
1444            saveButton.setVisibility(View.GONE);
1445            openButton.setVisibility(View.GONE);
1446            infoButton.setVisibility(View.GONE);
1447
1448            // If the attachment is queued, show the indeterminate progress bar.  From this point,.
1449            // any progress changes will cause this to be replaced by the normal progress bar
1450            if (AttachmentDownloadService.isAttachmentQueued(attachmentInfo.mId)) {
1451                attachmentInfo.showProgressIndeterminate();
1452                loadButton.setVisibility(View.GONE);
1453                cancelButton.setVisibility(View.VISIBLE);
1454            } else {
1455                loadButton.setVisibility(View.VISIBLE);
1456                cancelButton.setVisibility(View.GONE);
1457            }
1458        }
1459        openButton.setTag(attachmentInfo);
1460        saveButton.setTag(attachmentInfo);
1461        loadButton.setTag(attachmentInfo);
1462        infoButton.setTag(attachmentInfo);
1463        cancelButton.setTag(attachmentInfo);
1464    }
1465
1466    /**
1467     * Copy data from a cursor-refreshed attachment into the UI.  Called from UI thread.
1468     *
1469     * @param attachment A single attachment loaded from the provider
1470     */
1471    private void addAttachment(Attachment attachment) {
1472        LayoutInflater inflater = getActivity().getLayoutInflater();
1473        View view = inflater.inflate(R.layout.message_view_attachment, null);
1474
1475        TextView attachmentName = (TextView) UiUtilities.getView(view, R.id.attachment_name);
1476        TextView attachmentInfoView = (TextView) UiUtilities.getView(view, R.id.attachment_info);
1477        ImageView attachmentIcon = (ImageView) UiUtilities.getView(view, R.id.attachment_icon);
1478        Button openButton = (Button) UiUtilities.getView(view, R.id.open);
1479        Button saveButton = (Button) UiUtilities.getView(view, R.id.save);
1480        Button loadButton = (Button) UiUtilities.getView(view, R.id.load);
1481        Button infoButton = (Button) UiUtilities.getView(view, R.id.info);
1482        Button cancelButton = (Button) UiUtilities.getView(view, R.id.cancel);
1483        ProgressBar attachmentProgress = (ProgressBar) UiUtilities.getView(view, R.id.progress);
1484
1485        MessageViewAttachmentInfo attachmentInfo = new MessageViewAttachmentInfo(
1486                mContext, attachment, attachmentProgress);
1487
1488        // Check whether the attachment already exists
1489        if (Utility.attachmentExists(mContext, attachment)) {
1490            attachmentInfo.loaded = true;
1491        }
1492
1493        attachmentInfo.openButton = openButton;
1494        attachmentInfo.saveButton = saveButton;
1495        attachmentInfo.loadButton = loadButton;
1496        attachmentInfo.infoButton = infoButton;
1497        attachmentInfo.cancelButton = cancelButton;
1498        attachmentInfo.iconView = attachmentIcon;
1499
1500        updateAttachmentButtons(attachmentInfo);
1501
1502        view.setTag(attachmentInfo);
1503        openButton.setOnClickListener(this);
1504        saveButton.setOnClickListener(this);
1505        loadButton.setOnClickListener(this);
1506        infoButton.setOnClickListener(this);
1507        cancelButton.setOnClickListener(this);
1508
1509        attachmentName.setText(attachmentInfo.mName);
1510        attachmentInfoView.setText(UiUtilities.formatSize(mContext, attachmentInfo.mSize));
1511
1512        mAttachments.addView(view);
1513        mAttachments.setVisibility(View.VISIBLE);
1514    }
1515
1516    private MessageViewAttachmentInfo findAttachmentInfoFromView(long attachmentId) {
1517        for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
1518            MessageViewAttachmentInfo attachmentInfo =
1519                    (MessageViewAttachmentInfo) mAttachments.getChildAt(i).getTag();
1520            if (attachmentInfo.mId == attachmentId) {
1521                return attachmentInfo;
1522            }
1523        }
1524        return null;
1525    }
1526
1527    /**
1528     * Reload the UI from a provider cursor.  {@link LoadMessageTask#onPostExecute} calls it.
1529     *
1530     * Update the header views, and start loading the body.
1531     *
1532     * @param message A copy of the message loaded from the database
1533     * @param okToFetch If true, and message is not fully loaded, it's OK to fetch from
1534     * the network.  Use false to prevent looping here.
1535     */
1536    protected void reloadUiFromMessage(Message message, boolean okToFetch) {
1537        mMessage = message;
1538        mAccountId = message.mAccountKey;
1539
1540        mMessageObserver.register(ContentUris.withAppendedId(Message.CONTENT_URI, mMessage.mId));
1541
1542        updateHeaderView(mMessage);
1543
1544        // Handle partially-loaded email, as follows:
1545        // 1. Check value of message.mFlagLoaded
1546        // 2. If != LOADED, ask controller to load it
1547        // 3. Controller callback (after loaded) should trigger LoadBodyTask & LoadAttachmentsTask
1548        // 4. Else start the loader tasks right away (message already loaded)
1549        if (okToFetch && message.mFlagLoaded != Message.FLAG_LOADED_COMPLETE) {
1550            mControllerCallback.getWrappee().setWaitForLoadMessageId(message.mId);
1551            mController.loadMessageForView(message.mId);
1552        } else {
1553            Address[] fromList = Address.unpack(mMessage.mFrom);
1554            boolean autoShowImages = false;
1555            for (Address sender : fromList) {
1556                String email = sender.getAddress();
1557                if (shouldShowImagesFor(email)) {
1558                    autoShowImages = true;
1559                    break;
1560                }
1561            }
1562            mControllerCallback.getWrappee().setWaitForLoadMessageId(Message.NO_MESSAGE);
1563            // Ask for body
1564            new LoadBodyTask(message.mId, autoShowImages).executeParallel();
1565        }
1566    }
1567
1568    protected void updateHeaderView(Message message) {
1569        mSubjectView.setText(message.mSubject);
1570        final Address from = Address.unpackFirst(message.mFrom);
1571
1572        // Set sender address/display name
1573        // Note we set " " for empty field, so TextView's won't get squashed.
1574        // Otherwise their height will be 0, which breaks the layout.
1575        if (from != null) {
1576            final String fromFriendly = from.toFriendly();
1577            final String fromAddress = from.getAddress();
1578            mFromNameView.setText(fromFriendly);
1579            mFromAddressView.setText(fromFriendly.equals(fromAddress) ? " " : fromAddress);
1580        } else {
1581            mFromNameView.setText(" ");
1582            mFromAddressView.setText(" ");
1583        }
1584        mDateTimeView.setText(DateUtils.getRelativeTimeSpanString(mContext, message.mTimeStamp)
1585                .toString());
1586
1587        // To/Cc/Bcc
1588        final Resources res = mContext.getResources();
1589        final SpannableStringBuilder ssb = new SpannableStringBuilder();
1590        final String friendlyTo = Address.toFriendly(Address.unpack(message.mTo));
1591        final String friendlyCc = Address.toFriendly(Address.unpack(message.mCc));
1592        final String friendlyBcc = Address.toFriendly(Address.unpack(message.mBcc));
1593
1594        if (!TextUtils.isEmpty(friendlyTo)) {
1595            Utility.appendBold(ssb, res.getString(R.string.message_view_to_label));
1596            ssb.append(" ");
1597            ssb.append(friendlyTo);
1598        }
1599        if (!TextUtils.isEmpty(friendlyCc)) {
1600            ssb.append("  ");
1601            Utility.appendBold(ssb, res.getString(R.string.message_view_cc_label));
1602            ssb.append(" ");
1603            ssb.append(friendlyCc);
1604        }
1605        if (!TextUtils.isEmpty(friendlyBcc)) {
1606            ssb.append("  ");
1607            Utility.appendBold(ssb, res.getString(R.string.message_view_bcc_label));
1608            ssb.append(" ");
1609            ssb.append(friendlyBcc);
1610        }
1611        mAddressesView.setText(ssb);
1612    }
1613
1614    /**
1615     * @return the given date/time in a human readable form.  The returned string always have
1616     *     month and day (and year if {@code withYear} is set), so is usually long.
1617     *     Use {@link DateUtils#getRelativeTimeSpanString} instead to save the screen real estate.
1618     */
1619    private String formatDate(long millis, boolean withYear) {
1620        StringBuilder sb = new StringBuilder();
1621        Formatter formatter = new Formatter(sb);
1622        DateUtils.formatDateRange(mContext, formatter, millis, millis,
1623                DateUtils.FORMAT_SHOW_DATE
1624                | DateUtils.FORMAT_ABBREV_ALL
1625                | DateUtils.FORMAT_SHOW_TIME
1626                | (withYear ? DateUtils.FORMAT_SHOW_YEAR : DateUtils.FORMAT_NO_YEAR));
1627        return sb.toString();
1628    }
1629
1630    /**
1631     * Reload the body from the provider cursor.  This must only be called from the UI thread.
1632     *
1633     * @param bodyText text part
1634     * @param bodyHtml html part
1635     *
1636     * TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN??
1637     */
1638    private void reloadUiFromBody(String bodyText, String bodyHtml, boolean autoShowPictures) {
1639        String text = null;
1640        mHtmlTextRaw = null;
1641        boolean hasImages = false;
1642
1643        if (bodyHtml == null) {
1644            text = bodyText;
1645            /*
1646             * Convert the plain text to HTML
1647             */
1648            StringBuffer sb = new StringBuffer("<html><body>");
1649            if (text != null) {
1650                // Escape any inadvertent HTML in the text message
1651                text = EmailHtmlUtil.escapeCharacterToDisplay(text);
1652                // Find any embedded URL's and linkify
1653                Matcher m = Patterns.WEB_URL.matcher(text);
1654                while (m.find()) {
1655                    int start = m.start();
1656                    /*
1657                     * WEB_URL_PATTERN may match domain part of email address. To detect
1658                     * this false match, the character just before the matched string
1659                     * should not be '@'.
1660                     */
1661                    if (start == 0 || text.charAt(start - 1) != '@') {
1662                        String url = m.group();
1663                        Matcher proto = WEB_URL_PROTOCOL.matcher(url);
1664                        String link;
1665                        if (proto.find()) {
1666                            // This is work around to force URL protocol part be lower case,
1667                            // because WebView could follow only lower case protocol link.
1668                            link = proto.group().toLowerCase() + url.substring(proto.end());
1669                        } else {
1670                            // Patterns.WEB_URL matches URL without protocol part,
1671                            // so added default protocol to link.
1672                            link = "http://" + url;
1673                        }
1674                        String href = String.format("<a href=\"%s\">%s</a>", link, url);
1675                        m.appendReplacement(sb, href);
1676                    }
1677                    else {
1678                        m.appendReplacement(sb, "$0");
1679                    }
1680                }
1681                m.appendTail(sb);
1682            }
1683            sb.append("</body></html>");
1684            text = sb.toString();
1685        } else {
1686            text = bodyHtml;
1687            mHtmlTextRaw = bodyHtml;
1688            hasImages = IMG_TAG_START_REGEX.matcher(text).find();
1689        }
1690
1691        // TODO this is not really accurate.
1692        // - Images aren't the only network resources.  (e.g. CSS)
1693        // - If images are attached to the email and small enough, we download them at once,
1694        //   and won't need network access when they're shown.
1695        if (hasImages) {
1696            if (mRestoredPictureLoaded || autoShowPictures) {
1697                blockNetworkLoads(false);
1698                addTabFlags(TAB_FLAGS_PICTURE_LOADED); // Set for next onSaveInstanceState
1699
1700                // Make sure to reset the flag -- otherwise this will keep taking effect even after
1701                // moving to another message.
1702                mRestoredPictureLoaded = false;
1703            } else {
1704                addTabFlags(TAB_FLAGS_HAS_PICTURES);
1705            }
1706        }
1707        setMessageHtml(text);
1708
1709        // Ask for attachments after body
1710        new LoadAttachmentsTask().executeParallel(mMessage.mId);
1711
1712        mIsMessageLoadedForTest = true;
1713    }
1714
1715    /**
1716     * Overrides for WebView behaviors.
1717     */
1718    private class CustomWebViewClient extends WebViewClient {
1719        @Override
1720        public boolean shouldOverrideUrlLoading(WebView view, String url) {
1721            return mCallback.onUrlInMessageClicked(url);
1722        }
1723    }
1724
1725    private View findAttachmentView(long attachmentId) {
1726        for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
1727            View view = mAttachments.getChildAt(i);
1728            MessageViewAttachmentInfo attachment = (MessageViewAttachmentInfo) view.getTag();
1729            if (attachment.mId == attachmentId) {
1730                return view;
1731            }
1732        }
1733        return null;
1734    }
1735
1736    private MessageViewAttachmentInfo findAttachmentInfo(long attachmentId) {
1737        View view = findAttachmentView(attachmentId);
1738        if (view != null) {
1739            return (MessageViewAttachmentInfo)view.getTag();
1740        }
1741        return null;
1742    }
1743
1744    /**
1745     * Controller results listener.  We wrap it with {@link ControllerResultUiThreadWrapper},
1746     * so all methods are called on the UI thread.
1747     */
1748    private class ControllerResults extends Controller.Result {
1749        private long mWaitForLoadMessageId;
1750
1751        public void setWaitForLoadMessageId(long messageId) {
1752            mWaitForLoadMessageId = messageId;
1753        }
1754
1755        @Override
1756        public void loadMessageForViewCallback(MessagingException result, long accountId,
1757                long messageId, int progress) {
1758            if (messageId != mWaitForLoadMessageId) {
1759                // We are not waiting for this message to load, so exit quickly
1760                return;
1761            }
1762            if (result == null) {
1763                switch (progress) {
1764                    case 0:
1765                        mCallback.onLoadMessageStarted();
1766                        // Loading from network -- show the progress icon.
1767                        showContent(false, true);
1768                        break;
1769                    case 100:
1770                        mWaitForLoadMessageId = -1;
1771                        mCallback.onLoadMessageFinished();
1772                        // reload UI and reload everything else too
1773                        // pass false to LoadMessageTask to prevent looping here
1774                        cancelAllTasks();
1775                        new LoadMessageTask(false).executeParallel();
1776                        break;
1777                    default:
1778                        // do nothing - we don't have a progress bar at this time
1779                        break;
1780                }
1781            } else {
1782                mWaitForLoadMessageId = Message.NO_MESSAGE;
1783                String error = mContext.getString(R.string.status_network_error);
1784                mCallback.onLoadMessageError(error);
1785                resetView();
1786            }
1787        }
1788
1789        @Override
1790        public void loadAttachmentCallback(MessagingException result, long accountId,
1791                long messageId, long attachmentId, int progress) {
1792            if (messageId == mMessageId) {
1793                if (result == null) {
1794                    showAttachmentProgress(attachmentId, progress);
1795                    switch (progress) {
1796                        case 100:
1797                            final MessageViewAttachmentInfo attachmentInfo =
1798                                    findAttachmentInfoFromView(attachmentId);
1799                            if (attachmentInfo != null) {
1800                                updatePreviewIcon(attachmentInfo);
1801                            }
1802                            doFinishLoadAttachment(attachmentId);
1803                            break;
1804                        default:
1805                            // do nothing - we don't have a progress bar at this time
1806                            break;
1807                    }
1808                } else {
1809                    MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId);
1810                    if (attachment == null) {
1811                        // Called before LoadAttachmentsTask finishes.
1812                        // (Possible if you quickly close & re-open a message)
1813                        return;
1814                    }
1815                    attachment.cancelButton.setVisibility(View.GONE);
1816                    attachment.loadButton.setVisibility(View.VISIBLE);
1817                    attachment.hideProgress();
1818
1819                    final String error;
1820                    if (result.getCause() instanceof IOException) {
1821                        error = mContext.getString(R.string.status_network_error);
1822                    } else {
1823                        error = mContext.getString(
1824                                R.string.message_view_load_attachment_failed_toast,
1825                                attachment.mName);
1826                    }
1827                    mCallback.onLoadMessageError(error);
1828                }
1829            }
1830        }
1831
1832        private void showAttachmentProgress(long attachmentId, int progress) {
1833            MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId);
1834            if (attachment != null) {
1835                if (progress == 0) {
1836                    attachment.cancelButton.setVisibility(View.GONE);
1837                }
1838                attachment.showProgress(progress);
1839            }
1840        }
1841    }
1842
1843    /**
1844     * Class to detect update on the current message (e.g. toggle star).  When it gets content
1845     * change notifications, it kicks {@link ReloadMessageTask}.
1846     */
1847    private class MessageObserver extends ContentObserver implements Runnable {
1848        private final Throttle mThrottle;
1849        private final ContentResolver mContentResolver;
1850
1851        private boolean mRegistered;
1852
1853        public MessageObserver(Handler handler, Context context) {
1854            super(handler);
1855            mContentResolver = context.getContentResolver();
1856            mThrottle = new Throttle("MessageObserver", this, handler);
1857        }
1858
1859        public void unregister() {
1860            if (!mRegistered) {
1861                return;
1862            }
1863            mThrottle.cancelScheduledCallback();
1864            mContentResolver.unregisterContentObserver(this);
1865            mRegistered = false;
1866        }
1867
1868        public void register(Uri notifyUri) {
1869            unregister();
1870            mContentResolver.registerContentObserver(notifyUri, true, this);
1871            mRegistered = true;
1872        }
1873
1874        @Override
1875        public boolean deliverSelfNotifications() {
1876            return true;
1877        }
1878
1879        @Override
1880        public void onChange(boolean selfChange) {
1881            mThrottle.onEvent();
1882        }
1883
1884        /** This method is delay-called by {@link Throttle} on the UI thread. */
1885        @Override
1886        public void run() {
1887            // This method is delay-called, so need to make sure if it's still registered.
1888            if (mRegistered) {
1889                new ReloadMessageTask().cancelPreviousAndExecuteParallel();
1890            }
1891        }
1892    }
1893
1894    private void updatePreviewIcon(MessageViewAttachmentInfo attachmentInfo) {
1895        new UpdatePreviewIconTask(attachmentInfo).executeParallel();
1896    }
1897
1898    private class UpdatePreviewIconTask extends EmailAsyncTask<Void, Void, Bitmap> {
1899        @SuppressWarnings("hiding")
1900        private final Context mContext;
1901        private final MessageViewAttachmentInfo mAttachmentInfo;
1902
1903        public UpdatePreviewIconTask(MessageViewAttachmentInfo attachmentInfo) {
1904            super(mTaskTracker);
1905            mContext = getActivity();
1906            mAttachmentInfo = attachmentInfo;
1907        }
1908
1909        @Override
1910        protected Bitmap doInBackground(Void... params) {
1911            return getPreviewIcon(mContext, mAttachmentInfo);
1912        }
1913
1914        @Override
1915        protected void onSuccess(Bitmap result) {
1916            if (result == null) {
1917                return;
1918            }
1919            mAttachmentInfo.iconView.setImageBitmap(result);
1920        }
1921    }
1922
1923    private boolean shouldShowImagesFor(String senderEmail) {
1924        return Preferences.getPreferences(getActivity()).shouldShowImagesFor(senderEmail);
1925    }
1926
1927    private void setShowImagesForSender() {
1928        makeVisible(UiUtilities.getView(getView(), R.id.always_show_pictures_container), false);
1929
1930        // Force redraw of the container.
1931        updateTabs(mTabFlags);
1932
1933        Address[] fromList = Address.unpack(mMessage.mFrom);
1934        Preferences prefs = Preferences.getPreferences(getActivity());
1935        for (Address sender : fromList) {
1936            String email = sender.getAddress();
1937            prefs.setSenderAsTrusted(email);
1938        }
1939    }
1940
1941    public boolean isMessageLoadedForTest() {
1942        return mIsMessageLoadedForTest;
1943    }
1944
1945    public void clearIsMessageLoadedForTest() {
1946        mIsMessageLoadedForTest = true;
1947    }
1948}
1949