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