MessageViewFragmentBase.java revision 31e5beba35287258e20b0fff5b9138a3b0892221
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.body_text); 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) and the device density. The intention 519 * is for the text to be physically equal in size over different density 520 * screens. 521 */ 522 private int getWebViewZoom() { 523 float density = mContext.getResources().getDisplayMetrics().density; 524 int zoom = Preferences.getPreferences(mContext).getTextZoom(); 525 return (int) (ZOOM_SCALE_ARRAY[zoom] * density * 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.from_name: 963 case R.id.from_address: 964 case R.id.badge: 965 case R.id.presence: 966 onClickSender(); 967 break; 968 case R.id.load: 969 onLoadAttachment((MessageViewAttachmentInfo) view.getTag()); 970 break; 971 case R.id.info: 972 onInfoAttachment((MessageViewAttachmentInfo) view.getTag()); 973 break; 974 case R.id.save: 975 onSaveAttachment((MessageViewAttachmentInfo) view.getTag()); 976 break; 977 case R.id.open: 978 onOpenAttachment((MessageViewAttachmentInfo) view.getTag()); 979 break; 980 case R.id.cancel: 981 onCancelAttachment((MessageViewAttachmentInfo) view.getTag()); 982 break; 983 case R.id.show_message: 984 setCurrentTab(TAB_MESSAGE); 985 break; 986 case R.id.show_invite: 987 setCurrentTab(TAB_INVITE); 988 break; 989 case R.id.show_attachments: 990 setCurrentTab(TAB_ATTACHMENT); 991 break; 992 case R.id.show_pictures: 993 showPicturesInHtml(); 994 break; 995 case R.id.always_show_pictures_button: 996 setShowImagesForSender(); 997 break; 998 case R.id.sub_header_contents_collapsed: 999 showDetails(); 1000 break; 1001 case R.id.sub_header_contents_expanded: 1002 hideDetails(); 1003 break; 1004 } 1005 } 1006 1007 /** 1008 * Start loading contact photo and presence. 1009 */ 1010 private void queryContactStatus() { 1011 if (!isMessageOpen()) return; 1012 initContactStatusViews(); // Initialize the state, just in case. 1013 1014 // Find the sender email address, and start presence check. 1015 Address sender = Address.unpackFirst(mMessage.mFrom); 1016 if (sender != null) { 1017 String email = sender.getAddress(); 1018 if (email != null) { 1019 getLoaderManager().restartLoader(PHOTO_LOADER_ID, 1020 ContactStatusLoaderCallbacks.createArguments(email), 1021 new ContactStatusLoaderCallbacks(this)); 1022 } 1023 } 1024 } 1025 1026 /** 1027 * Called by {@link LoadMessageTask} and {@link ReloadMessageTask} to load a message in a 1028 * subclass specific way. 1029 * 1030 * NOTE This method is called on a worker thread! Implementations must properly synchronize 1031 * when accessing members. 1032 * 1033 * @param activity the parent activity. Subclass use it as a context, and to show a toast. 1034 */ 1035 protected abstract Message openMessageSync(Activity activity); 1036 1037 /** 1038 * Called in a background thread to reload a new copy of the Message in case something has 1039 * changed. 1040 */ 1041 protected Message reloadMessageSync(Activity activity) { 1042 return openMessageSync(activity); 1043 } 1044 1045 /** 1046 * Async task for loading a single message outside of the UI thread 1047 */ 1048 private class LoadMessageTask extends EmailAsyncTask<Void, Void, Message> { 1049 1050 private final boolean mOkToFetch; 1051 private Mailbox mMailbox; 1052 1053 /** 1054 * Special constructor to cache some local info 1055 */ 1056 public LoadMessageTask(boolean okToFetch) { 1057 super(mTaskTracker); 1058 mOkToFetch = okToFetch; 1059 } 1060 1061 @Override 1062 protected Message doInBackground(Void... params) { 1063 Activity activity = getActivity(); 1064 Message message = null; 1065 if (activity != null) { 1066 message = openMessageSync(activity); 1067 } 1068 if (message != null) { 1069 mMailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey); 1070 if (mMailbox == null) { 1071 message = null; // mailbox removed?? 1072 } 1073 } 1074 return message; 1075 } 1076 1077 @Override 1078 protected void onSuccess(Message message) { 1079 if (message == null) { 1080 resetView(); 1081 mCallback.onMessageNotExists(); 1082 return; 1083 } 1084 mMessageId = message.mId; 1085 1086 reloadUiFromMessage(message, mOkToFetch); 1087 queryContactStatus(); 1088 onMessageShown(mMessageId, mMailbox); 1089 RecentMailboxManager.getInstance(mContext).touch(mAccountId, message.mMailboxKey); 1090 } 1091 } 1092 1093 /** 1094 * Kicked by {@link MessageObserver}. Reload the message and update the views. 1095 */ 1096 private class ReloadMessageTask extends EmailAsyncTask<Void, Void, Message> { 1097 public ReloadMessageTask() { 1098 super(mTaskTracker); 1099 } 1100 1101 @Override 1102 protected Message doInBackground(Void... params) { 1103 Activity activity = getActivity(); 1104 if (activity == null) { 1105 return null; 1106 } else { 1107 return reloadMessageSync(activity); 1108 } 1109 } 1110 1111 @Override 1112 protected void onSuccess(Message message) { 1113 if (message == null || message.mMailboxKey != mMessage.mMailboxKey) { 1114 // Message deleted or moved. 1115 mCallback.onMessageNotExists(); 1116 return; 1117 } 1118 mMessage = message; 1119 updateHeaderView(mMessage); 1120 } 1121 } 1122 1123 /** 1124 * Called when a message is shown to the user. 1125 */ 1126 protected void onMessageShown(long messageId, Mailbox mailbox) { 1127 } 1128 1129 /** 1130 * Called when the message body is loaded. 1131 */ 1132 protected void onPostLoadBody() { 1133 } 1134 1135 /** 1136 * Async task for loading a single message body outside of the UI thread 1137 */ 1138 private class LoadBodyTask extends EmailAsyncTask<Void, Void, String[]> { 1139 1140 private final long mId; 1141 private boolean mErrorLoadingMessageBody; 1142 private final boolean mAutoShowPictures; 1143 1144 /** 1145 * Special constructor to cache some local info 1146 */ 1147 public LoadBodyTask(long messageId, boolean autoShowPictures) { 1148 super(mTaskTracker); 1149 mId = messageId; 1150 mAutoShowPictures = autoShowPictures; 1151 } 1152 1153 @Override 1154 protected String[] doInBackground(Void... params) { 1155 try { 1156 String text = null; 1157 String html = Body.restoreBodyHtmlWithMessageId(mContext, mId); 1158 if (html == null) { 1159 text = Body.restoreBodyTextWithMessageId(mContext, mId); 1160 } 1161 return new String[] { text, html }; 1162 } catch (RuntimeException re) { 1163 // This catches SQLiteException as well as other RTE's we've seen from the 1164 // database calls, such as IllegalStateException 1165 Log.d(Logging.LOG_TAG, "Exception while loading message body", re); 1166 mErrorLoadingMessageBody = true; 1167 return null; 1168 } 1169 } 1170 1171 @Override 1172 protected void onSuccess(String[] results) { 1173 if (results == null) { 1174 if (mErrorLoadingMessageBody) { 1175 Utility.showToast(getActivity(), R.string.error_loading_message_body); 1176 } 1177 resetView(); 1178 return; 1179 } 1180 reloadUiFromBody(results[0], results[1], mAutoShowPictures); // text, html 1181 onPostLoadBody(); 1182 } 1183 } 1184 1185 /** 1186 * Async task for loading attachments 1187 * 1188 * Note: This really should only be called when the message load is complete - or, we should 1189 * leave open a listener so the attachments can fill in as they are discovered. In either case, 1190 * this implementation is incomplete, as it will fail to refresh properly if the message is 1191 * partially loaded at this time. 1192 */ 1193 private class LoadAttachmentsTask extends EmailAsyncTask<Long, Void, Attachment[]> { 1194 public LoadAttachmentsTask() { 1195 super(mTaskTracker); 1196 } 1197 1198 @Override 1199 protected Attachment[] doInBackground(Long... messageIds) { 1200 return Attachment.restoreAttachmentsWithMessageId(mContext, messageIds[0]); 1201 } 1202 1203 @Override 1204 protected void onSuccess(Attachment[] attachments) { 1205 try { 1206 if (attachments == null) { 1207 return; 1208 } 1209 boolean htmlChanged = false; 1210 int numDisplayedAttachments = 0; 1211 for (Attachment attachment : attachments) { 1212 if (mHtmlTextRaw != null && attachment.mContentId != null 1213 && attachment.mContentUri != null) { 1214 // for html body, replace CID for inline images 1215 // Regexp which matches ' src="cid:contentId"'. 1216 String contentIdRe = 1217 "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\""; 1218 String srcContentUri = " src=\"" + attachment.mContentUri + "\""; 1219 mHtmlTextRaw = mHtmlTextRaw.replaceAll(contentIdRe, srcContentUri); 1220 htmlChanged = true; 1221 } else { 1222 addAttachment(attachment); 1223 numDisplayedAttachments++; 1224 } 1225 } 1226 setAttachmentCount(numDisplayedAttachments); 1227 mHtmlTextWebView = mHtmlTextRaw; 1228 mHtmlTextRaw = null; 1229 if (htmlChanged) { 1230 setMessageHtml(mHtmlTextWebView); 1231 } 1232 } finally { 1233 showContent(true, false); 1234 } 1235 } 1236 } 1237 1238 private static Bitmap getPreviewIcon(Context context, AttachmentInfo attachment) { 1239 try { 1240 return BitmapFactory.decodeStream( 1241 context.getContentResolver().openInputStream( 1242 AttachmentUtilities.getAttachmentThumbnailUri( 1243 attachment.mAccountKey, attachment.mId, 1244 PREVIEW_ICON_WIDTH, 1245 PREVIEW_ICON_HEIGHT))); 1246 } catch (Exception e) { 1247 Log.d(Logging.LOG_TAG, "Attachment preview failed with exception " + e.getMessage()); 1248 return null; 1249 } 1250 } 1251 1252 /** 1253 * Subclass of AttachmentInfo which includes our views and buttons related to attachment 1254 * handling, as well as our determination of suitability for viewing (based on availability of 1255 * a viewer app) and saving (based upon the presence of external storage) 1256 */ 1257 private static class MessageViewAttachmentInfo extends AttachmentInfo { 1258 private Button openButton; 1259 private Button saveButton; 1260 private Button loadButton; 1261 private Button infoButton; 1262 private Button cancelButton; 1263 private ImageView iconView; 1264 1265 private static final Map<AttachmentInfo, String> sSavedFileInfos = Maps.newHashMap(); 1266 1267 // Don't touch it directly from the outer class. 1268 private final ProgressBar mProgressView; 1269 private boolean loaded; 1270 1271 private MessageViewAttachmentInfo(Context context, Attachment attachment, 1272 ProgressBar progressView) { 1273 super(context, attachment); 1274 mProgressView = progressView; 1275 } 1276 1277 /** 1278 * Create a new attachment info based upon an existing attachment info. Display 1279 * related fields (such as views and buttons) are copied from old to new. 1280 */ 1281 private MessageViewAttachmentInfo(Context context, MessageViewAttachmentInfo oldInfo) { 1282 super(context, oldInfo); 1283 openButton = oldInfo.openButton; 1284 saveButton = oldInfo.saveButton; 1285 loadButton = oldInfo.loadButton; 1286 infoButton = oldInfo.infoButton; 1287 cancelButton = oldInfo.cancelButton; 1288 iconView = oldInfo.iconView; 1289 mProgressView = oldInfo.mProgressView; 1290 loaded = oldInfo.loaded; 1291 } 1292 1293 public void hideProgress() { 1294 // Don't use GONE, which'll break the layout. 1295 if (mProgressView.getVisibility() != View.INVISIBLE) { 1296 mProgressView.setVisibility(View.INVISIBLE); 1297 } 1298 } 1299 1300 public void showProgress(int progress) { 1301 if (mProgressView.getVisibility() != View.VISIBLE) { 1302 mProgressView.setVisibility(View.VISIBLE); 1303 } 1304 if (mProgressView.isIndeterminate()) { 1305 mProgressView.setIndeterminate(false); 1306 } 1307 mProgressView.setProgress(progress); 1308 1309 // Hide on completion. 1310 if (progress == 100) { 1311 hideProgress(); 1312 } 1313 } 1314 1315 public void showProgressIndeterminate() { 1316 if (mProgressView.getVisibility() != View.VISIBLE) { 1317 mProgressView.setVisibility(View.VISIBLE); 1318 } 1319 if (!mProgressView.isIndeterminate()) { 1320 mProgressView.setIndeterminate(true); 1321 } 1322 } 1323 1324 /** 1325 * Determines whether or not this attachment has a saved file in the external storage. That 1326 * is, the user has at some point clicked "save" for this attachment. 1327 * 1328 * Note: this is an approximation and uses an in-memory cache that can get wiped when the 1329 * process dies, and so is somewhat conservative. Additionally, the user can modify the file 1330 * after saving, and so the file may not be the same (though this is unlikely). 1331 */ 1332 public boolean isFileSaved() { 1333 String path = getSavedPath(); 1334 if (path == null) { 1335 return false; 1336 } 1337 boolean savedFileExists = new File(path).exists(); 1338 if (!savedFileExists) { 1339 // Purge the cache entry. 1340 setSavedPath(null); 1341 } 1342 return savedFileExists; 1343 } 1344 1345 private void setSavedPath(String path) { 1346 if (path == null) { 1347 sSavedFileInfos.remove(this); 1348 } else { 1349 sSavedFileInfos.put(this, path); 1350 } 1351 } 1352 1353 /** 1354 * Returns an absolute file path for the given attachment if it has been saved. If one is 1355 * not found, {@code null} is returned. 1356 * 1357 * Clients are expected to validate that the file at the given path is still valid. 1358 */ 1359 private String getSavedPath() { 1360 return sSavedFileInfos.get(this); 1361 } 1362 1363 @Override 1364 protected Uri getUriForIntent(Context context, long accountId) { 1365 // Prefer to act on the saved file for intents. 1366 String path = getSavedPath(); 1367 return (path != null) 1368 ? Uri.parse("file://" + getSavedPath()) 1369 : super.getUriForIntent(context, accountId); 1370 } 1371 } 1372 1373 /** 1374 * Updates all current attachments on the attachment tab. 1375 */ 1376 private void updateAttachmentTab() { 1377 for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { 1378 View view = mAttachments.getChildAt(i); 1379 MessageViewAttachmentInfo oldInfo = (MessageViewAttachmentInfo)view.getTag(); 1380 MessageViewAttachmentInfo newInfo = 1381 new MessageViewAttachmentInfo(getActivity(), oldInfo); 1382 updateAttachmentButtons(newInfo); 1383 view.setTag(newInfo); 1384 } 1385 } 1386 1387 /** 1388 * Updates the attachment buttons. Adjusts the visibility of the buttons as well 1389 * as updating any tag information associated with the buttons. 1390 */ 1391 private void updateAttachmentButtons(MessageViewAttachmentInfo attachmentInfo) { 1392 ImageView attachmentIcon = attachmentInfo.iconView; 1393 Button openButton = attachmentInfo.openButton; 1394 Button saveButton = attachmentInfo.saveButton; 1395 Button loadButton = attachmentInfo.loadButton; 1396 Button infoButton = attachmentInfo.infoButton; 1397 Button cancelButton = attachmentInfo.cancelButton; 1398 1399 if (!attachmentInfo.mAllowView) { 1400 openButton.setVisibility(View.GONE); 1401 } 1402 if (!attachmentInfo.mAllowSave) { 1403 saveButton.setVisibility(View.GONE); 1404 } 1405 1406 if (!attachmentInfo.mAllowView && !attachmentInfo.mAllowSave) { 1407 // This attachment may never be viewed or saved, so block everything 1408 attachmentInfo.hideProgress(); 1409 openButton.setVisibility(View.GONE); 1410 saveButton.setVisibility(View.GONE); 1411 loadButton.setVisibility(View.GONE); 1412 cancelButton.setVisibility(View.GONE); 1413 infoButton.setVisibility(View.VISIBLE); 1414 } else if (attachmentInfo.loaded) { 1415 // If the attachment is loaded, show 100% progress 1416 // Note that for POP3 messages, the user will only see "Open" and "Save", 1417 // because the entire message is loaded before being shown. 1418 // Hide "Load" and "Info", show "View" and "Save" 1419 attachmentInfo.showProgress(100); 1420 if (attachmentInfo.mAllowSave) { 1421 saveButton.setVisibility(View.VISIBLE); 1422 1423 boolean isFileSaved = attachmentInfo.isFileSaved(); 1424 saveButton.setEnabled(!isFileSaved); 1425 if (!isFileSaved) { 1426 saveButton.setText(R.string.message_view_attachment_save_action); 1427 } else { 1428 saveButton.setText(R.string.message_view_attachment_saved); 1429 } 1430 } 1431 if (attachmentInfo.mAllowView) { 1432 // Set the attachment action button text accordingly 1433 if (attachmentInfo.mContentType.startsWith("audio/") || 1434 attachmentInfo.mContentType.startsWith("video/")) { 1435 openButton.setText(R.string.message_view_attachment_play_action); 1436 } else if (attachmentInfo.mAllowInstall) { 1437 openButton.setText(R.string.message_view_attachment_install_action); 1438 } else { 1439 openButton.setText(R.string.message_view_attachment_view_action); 1440 } 1441 openButton.setVisibility(View.VISIBLE); 1442 } 1443 if (attachmentInfo.mDenyFlags == AttachmentInfo.ALLOW) { 1444 infoButton.setVisibility(View.GONE); 1445 } else { 1446 infoButton.setVisibility(View.VISIBLE); 1447 } 1448 loadButton.setVisibility(View.GONE); 1449 cancelButton.setVisibility(View.GONE); 1450 1451 updatePreviewIcon(attachmentInfo); 1452 } else { 1453 // The attachment is not loaded, so present UI to start downloading it 1454 1455 // Show "Load"; hide "View", "Save" and "Info" 1456 saveButton.setVisibility(View.GONE); 1457 openButton.setVisibility(View.GONE); 1458 infoButton.setVisibility(View.GONE); 1459 1460 // If the attachment is queued, show the indeterminate progress bar. From this point,. 1461 // any progress changes will cause this to be replaced by the normal progress bar 1462 if (AttachmentDownloadService.isAttachmentQueued(attachmentInfo.mId)) { 1463 attachmentInfo.showProgressIndeterminate(); 1464 loadButton.setVisibility(View.GONE); 1465 cancelButton.setVisibility(View.VISIBLE); 1466 } else { 1467 loadButton.setVisibility(View.VISIBLE); 1468 cancelButton.setVisibility(View.GONE); 1469 } 1470 } 1471 openButton.setTag(attachmentInfo); 1472 saveButton.setTag(attachmentInfo); 1473 loadButton.setTag(attachmentInfo); 1474 infoButton.setTag(attachmentInfo); 1475 cancelButton.setTag(attachmentInfo); 1476 } 1477 1478 /** 1479 * Copy data from a cursor-refreshed attachment into the UI. Called from UI thread. 1480 * 1481 * @param attachment A single attachment loaded from the provider 1482 */ 1483 private void addAttachment(Attachment attachment) { 1484 LayoutInflater inflater = getActivity().getLayoutInflater(); 1485 View view = inflater.inflate(R.layout.message_view_attachment, null); 1486 1487 TextView attachmentName = (TextView) UiUtilities.getView(view, R.id.attachment_name); 1488 TextView attachmentInfoView = (TextView) UiUtilities.getView(view, R.id.attachment_info); 1489 ImageView attachmentIcon = (ImageView) UiUtilities.getView(view, R.id.attachment_icon); 1490 Button openButton = (Button) UiUtilities.getView(view, R.id.open); 1491 Button saveButton = (Button) UiUtilities.getView(view, R.id.save); 1492 Button loadButton = (Button) UiUtilities.getView(view, R.id.load); 1493 Button infoButton = (Button) UiUtilities.getView(view, R.id.info); 1494 Button cancelButton = (Button) UiUtilities.getView(view, R.id.cancel); 1495 ProgressBar attachmentProgress = (ProgressBar) UiUtilities.getView(view, R.id.progress); 1496 1497 MessageViewAttachmentInfo attachmentInfo = new MessageViewAttachmentInfo( 1498 mContext, attachment, attachmentProgress); 1499 1500 // Check whether the attachment already exists 1501 if (Utility.attachmentExists(mContext, attachment)) { 1502 attachmentInfo.loaded = true; 1503 } 1504 1505 attachmentInfo.openButton = openButton; 1506 attachmentInfo.saveButton = saveButton; 1507 attachmentInfo.loadButton = loadButton; 1508 attachmentInfo.infoButton = infoButton; 1509 attachmentInfo.cancelButton = cancelButton; 1510 attachmentInfo.iconView = attachmentIcon; 1511 1512 updateAttachmentButtons(attachmentInfo); 1513 1514 view.setTag(attachmentInfo); 1515 openButton.setOnClickListener(this); 1516 saveButton.setOnClickListener(this); 1517 loadButton.setOnClickListener(this); 1518 infoButton.setOnClickListener(this); 1519 cancelButton.setOnClickListener(this); 1520 1521 attachmentName.setText(attachmentInfo.mName); 1522 attachmentInfoView.setText(UiUtilities.formatSize(mContext, attachmentInfo.mSize)); 1523 1524 mAttachments.addView(view); 1525 mAttachments.setVisibility(View.VISIBLE); 1526 } 1527 1528 private MessageViewAttachmentInfo findAttachmentInfoFromView(long attachmentId) { 1529 for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { 1530 MessageViewAttachmentInfo attachmentInfo = 1531 (MessageViewAttachmentInfo) mAttachments.getChildAt(i).getTag(); 1532 if (attachmentInfo.mId == attachmentId) { 1533 return attachmentInfo; 1534 } 1535 } 1536 return null; 1537 } 1538 1539 /** 1540 * Reload the UI from a provider cursor. {@link LoadMessageTask#onSuccess} calls it. 1541 * 1542 * Update the header views, and start loading the body. 1543 * 1544 * @param message A copy of the message loaded from the database 1545 * @param okToFetch If true, and message is not fully loaded, it's OK to fetch from 1546 * the network. Use false to prevent looping here. 1547 */ 1548 protected void reloadUiFromMessage(Message message, boolean okToFetch) { 1549 mMessage = message; 1550 mAccountId = message.mAccountKey; 1551 1552 mMessageObserver.register(ContentUris.withAppendedId(Message.CONTENT_URI, mMessage.mId)); 1553 1554 updateHeaderView(mMessage); 1555 1556 // Handle partially-loaded email, as follows: 1557 // 1. Check value of message.mFlagLoaded 1558 // 2. If != LOADED, ask controller to load it 1559 // 3. Controller callback (after loaded) should trigger LoadBodyTask & LoadAttachmentsTask 1560 // 4. Else start the loader tasks right away (message already loaded) 1561 if (okToFetch && message.mFlagLoaded != Message.FLAG_LOADED_COMPLETE) { 1562 mControllerCallback.getWrappee().setWaitForLoadMessageId(message.mId); 1563 mController.loadMessageForView(message.mId); 1564 } else { 1565 Address[] fromList = Address.unpack(mMessage.mFrom); 1566 boolean autoShowImages = false; 1567 for (Address sender : fromList) { 1568 String email = sender.getAddress(); 1569 if (shouldShowImagesFor(email)) { 1570 autoShowImages = true; 1571 break; 1572 } 1573 } 1574 mControllerCallback.getWrappee().setWaitForLoadMessageId(Message.NO_MESSAGE); 1575 // Ask for body 1576 new LoadBodyTask(message.mId, autoShowImages).executeParallel(); 1577 } 1578 } 1579 1580 protected void updateHeaderView(Message message) { 1581 mSubjectView.setText(message.mSubject); 1582 final Address from = Address.unpackFirst(message.mFrom); 1583 1584 // Set sender address/display name 1585 // Note we set " " for empty field, so TextView's won't get squashed. 1586 // Otherwise their height will be 0, which breaks the layout. 1587 if (from != null) { 1588 final String fromFriendly = from.toFriendly(); 1589 final String fromAddress = from.getAddress(); 1590 mFromNameView.setText(fromFriendly); 1591 mFromAddressView.setText(fromFriendly.equals(fromAddress) ? " " : fromAddress); 1592 } else { 1593 mFromNameView.setText(" "); 1594 mFromAddressView.setText(" "); 1595 } 1596 mDateTimeView.setText(DateUtils.getRelativeTimeSpanString(mContext, message.mTimeStamp) 1597 .toString()); 1598 1599 // To/Cc/Bcc 1600 final Resources res = mContext.getResources(); 1601 final SpannableStringBuilder ssb = new SpannableStringBuilder(); 1602 final String friendlyTo = Address.toFriendly(Address.unpack(message.mTo)); 1603 final String friendlyCc = Address.toFriendly(Address.unpack(message.mCc)); 1604 final String friendlyBcc = Address.toFriendly(Address.unpack(message.mBcc)); 1605 1606 if (!TextUtils.isEmpty(friendlyTo)) { 1607 Utility.appendBold(ssb, res.getString(R.string.message_view_to_label)); 1608 ssb.append(" "); 1609 ssb.append(friendlyTo); 1610 } 1611 if (!TextUtils.isEmpty(friendlyCc)) { 1612 ssb.append(" "); 1613 Utility.appendBold(ssb, res.getString(R.string.message_view_cc_label)); 1614 ssb.append(" "); 1615 ssb.append(friendlyCc); 1616 } 1617 if (!TextUtils.isEmpty(friendlyBcc)) { 1618 ssb.append(" "); 1619 Utility.appendBold(ssb, res.getString(R.string.message_view_bcc_label)); 1620 ssb.append(" "); 1621 ssb.append(friendlyBcc); 1622 } 1623 mAddressesView.setText(ssb); 1624 } 1625 1626 /** 1627 * @return the given date/time in a human readable form. The returned string always have 1628 * month and day (and year if {@code withYear} is set), so is usually long. 1629 * Use {@link DateUtils#getRelativeTimeSpanString} instead to save the screen real estate. 1630 */ 1631 private String formatDate(long millis, boolean withYear) { 1632 StringBuilder sb = new StringBuilder(); 1633 Formatter formatter = new Formatter(sb); 1634 DateUtils.formatDateRange(mContext, formatter, millis, millis, 1635 DateUtils.FORMAT_SHOW_DATE 1636 | DateUtils.FORMAT_ABBREV_ALL 1637 | DateUtils.FORMAT_SHOW_TIME 1638 | (withYear ? DateUtils.FORMAT_SHOW_YEAR : DateUtils.FORMAT_NO_YEAR)); 1639 return sb.toString(); 1640 } 1641 1642 /** 1643 * Reload the body from the provider cursor. This must only be called from the UI thread. 1644 * 1645 * @param bodyText text part 1646 * @param bodyHtml html part 1647 * 1648 * TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN?? 1649 */ 1650 private void reloadUiFromBody(String bodyText, String bodyHtml, boolean autoShowPictures) { 1651 String text = null; 1652 mHtmlTextRaw = null; 1653 boolean hasImages = false; 1654 1655 if (bodyHtml == null) { 1656 text = bodyText; 1657 /* 1658 * Convert the plain text to HTML 1659 */ 1660 StringBuffer sb = new StringBuffer("<html><body>"); 1661 if (text != null) { 1662 // Escape any inadvertent HTML in the text message 1663 text = EmailHtmlUtil.escapeCharacterToDisplay(text); 1664 // Find any embedded URL's and linkify 1665 Matcher m = Patterns.WEB_URL.matcher(text); 1666 while (m.find()) { 1667 int start = m.start(); 1668 /* 1669 * WEB_URL_PATTERN may match domain part of email address. To detect 1670 * this false match, the character just before the matched string 1671 * should not be '@'. 1672 */ 1673 if (start == 0 || text.charAt(start - 1) != '@') { 1674 String url = m.group(); 1675 Matcher proto = WEB_URL_PROTOCOL.matcher(url); 1676 String link; 1677 if (proto.find()) { 1678 // This is work around to force URL protocol part be lower case, 1679 // because WebView could follow only lower case protocol link. 1680 link = proto.group().toLowerCase() + url.substring(proto.end()); 1681 } else { 1682 // Patterns.WEB_URL matches URL without protocol part, 1683 // so added default protocol to link. 1684 link = "http://" + url; 1685 } 1686 String href = String.format("<a href=\"%s\">%s</a>", link, url); 1687 m.appendReplacement(sb, href); 1688 } 1689 else { 1690 m.appendReplacement(sb, "$0"); 1691 } 1692 } 1693 m.appendTail(sb); 1694 } 1695 sb.append("</body></html>"); 1696 text = sb.toString(); 1697 } else { 1698 text = bodyHtml; 1699 mHtmlTextRaw = bodyHtml; 1700 hasImages = IMG_TAG_START_REGEX.matcher(text).find(); 1701 } 1702 1703 // TODO this is not really accurate. 1704 // - Images aren't the only network resources. (e.g. CSS) 1705 // - If images are attached to the email and small enough, we download them at once, 1706 // and won't need network access when they're shown. 1707 if (hasImages) { 1708 if (mRestoredPictureLoaded || autoShowPictures) { 1709 blockNetworkLoads(false); 1710 addTabFlags(TAB_FLAGS_PICTURE_LOADED); // Set for next onSaveInstanceState 1711 1712 // Make sure to reset the flag -- otherwise this will keep taking effect even after 1713 // moving to another message. 1714 mRestoredPictureLoaded = false; 1715 } else { 1716 addTabFlags(TAB_FLAGS_HAS_PICTURES); 1717 } 1718 } 1719 setMessageHtml(text); 1720 1721 // Ask for attachments after body 1722 new LoadAttachmentsTask().executeParallel(mMessage.mId); 1723 1724 mIsMessageLoadedForTest = true; 1725 } 1726 1727 /** 1728 * Overrides for WebView behaviors. 1729 */ 1730 private class CustomWebViewClient extends WebViewClient { 1731 @Override 1732 public boolean shouldOverrideUrlLoading(WebView view, String url) { 1733 return mCallback.onUrlInMessageClicked(url); 1734 } 1735 } 1736 1737 private View findAttachmentView(long attachmentId) { 1738 for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { 1739 View view = mAttachments.getChildAt(i); 1740 MessageViewAttachmentInfo attachment = (MessageViewAttachmentInfo) view.getTag(); 1741 if (attachment.mId == attachmentId) { 1742 return view; 1743 } 1744 } 1745 return null; 1746 } 1747 1748 private MessageViewAttachmentInfo findAttachmentInfo(long attachmentId) { 1749 View view = findAttachmentView(attachmentId); 1750 if (view != null) { 1751 return (MessageViewAttachmentInfo)view.getTag(); 1752 } 1753 return null; 1754 } 1755 1756 /** 1757 * Controller results listener. We wrap it with {@link ControllerResultUiThreadWrapper}, 1758 * so all methods are called on the UI thread. 1759 */ 1760 private class ControllerResults extends Controller.Result { 1761 private long mWaitForLoadMessageId; 1762 1763 public void setWaitForLoadMessageId(long messageId) { 1764 mWaitForLoadMessageId = messageId; 1765 } 1766 1767 @Override 1768 public void loadMessageForViewCallback(MessagingException result, long accountId, 1769 long messageId, int progress) { 1770 if (messageId != mWaitForLoadMessageId) { 1771 // We are not waiting for this message to load, so exit quickly 1772 return; 1773 } 1774 if (result == null) { 1775 switch (progress) { 1776 case 0: 1777 mCallback.onLoadMessageStarted(); 1778 // Loading from network -- show the progress icon. 1779 showContent(false, true); 1780 break; 1781 case 100: 1782 mWaitForLoadMessageId = -1; 1783 mCallback.onLoadMessageFinished(); 1784 // reload UI and reload everything else too 1785 // pass false to LoadMessageTask to prevent looping here 1786 cancelAllTasks(); 1787 new LoadMessageTask(false).executeParallel(); 1788 break; 1789 default: 1790 // do nothing - we don't have a progress bar at this time 1791 break; 1792 } 1793 } else { 1794 mWaitForLoadMessageId = Message.NO_MESSAGE; 1795 String error = mContext.getString(R.string.status_network_error); 1796 mCallback.onLoadMessageError(error); 1797 resetView(); 1798 } 1799 } 1800 1801 @Override 1802 public void loadAttachmentCallback(MessagingException result, long accountId, 1803 long messageId, long attachmentId, int progress) { 1804 if (messageId == mMessageId) { 1805 if (result == null) { 1806 showAttachmentProgress(attachmentId, progress); 1807 switch (progress) { 1808 case 100: 1809 final MessageViewAttachmentInfo attachmentInfo = 1810 findAttachmentInfoFromView(attachmentId); 1811 if (attachmentInfo != null) { 1812 updatePreviewIcon(attachmentInfo); 1813 } 1814 doFinishLoadAttachment(attachmentId); 1815 break; 1816 default: 1817 // do nothing - we don't have a progress bar at this time 1818 break; 1819 } 1820 } else { 1821 MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId); 1822 if (attachment == null) { 1823 // Called before LoadAttachmentsTask finishes. 1824 // (Possible if you quickly close & re-open a message) 1825 return; 1826 } 1827 attachment.cancelButton.setVisibility(View.GONE); 1828 attachment.loadButton.setVisibility(View.VISIBLE); 1829 attachment.hideProgress(); 1830 1831 final String error; 1832 if (result.getCause() instanceof IOException) { 1833 error = mContext.getString(R.string.status_network_error); 1834 } else { 1835 error = mContext.getString( 1836 R.string.message_view_load_attachment_failed_toast, 1837 attachment.mName); 1838 } 1839 mCallback.onLoadMessageError(error); 1840 } 1841 } 1842 } 1843 1844 private void showAttachmentProgress(long attachmentId, int progress) { 1845 MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId); 1846 if (attachment != null) { 1847 if (progress == 0) { 1848 attachment.cancelButton.setVisibility(View.GONE); 1849 } 1850 attachment.showProgress(progress); 1851 } 1852 } 1853 } 1854 1855 /** 1856 * Class to detect update on the current message (e.g. toggle star). When it gets content 1857 * change notifications, it kicks {@link ReloadMessageTask}. 1858 */ 1859 private class MessageObserver extends ContentObserver implements Runnable { 1860 private final Throttle mThrottle; 1861 private final ContentResolver mContentResolver; 1862 1863 private boolean mRegistered; 1864 1865 public MessageObserver(Handler handler, Context context) { 1866 super(handler); 1867 mContentResolver = context.getContentResolver(); 1868 mThrottle = new Throttle("MessageObserver", this, handler); 1869 } 1870 1871 public void unregister() { 1872 if (!mRegistered) { 1873 return; 1874 } 1875 mThrottle.cancelScheduledCallback(); 1876 mContentResolver.unregisterContentObserver(this); 1877 mRegistered = false; 1878 } 1879 1880 public void register(Uri notifyUri) { 1881 unregister(); 1882 mContentResolver.registerContentObserver(notifyUri, true, this); 1883 mRegistered = true; 1884 } 1885 1886 @Override 1887 public boolean deliverSelfNotifications() { 1888 return true; 1889 } 1890 1891 @Override 1892 public void onChange(boolean selfChange) { 1893 if (mRegistered) { 1894 mThrottle.onEvent(); 1895 } 1896 } 1897 1898 /** This method is delay-called by {@link Throttle} on the UI thread. */ 1899 @Override 1900 public void run() { 1901 // This method is delay-called, so need to make sure if it's still registered. 1902 if (mRegistered) { 1903 new ReloadMessageTask().cancelPreviousAndExecuteParallel(); 1904 } 1905 } 1906 } 1907 1908 private void updatePreviewIcon(MessageViewAttachmentInfo attachmentInfo) { 1909 new UpdatePreviewIconTask(attachmentInfo).executeParallel(); 1910 } 1911 1912 private class UpdatePreviewIconTask extends EmailAsyncTask<Void, Void, Bitmap> { 1913 @SuppressWarnings("hiding") 1914 private final Context mContext; 1915 private final MessageViewAttachmentInfo mAttachmentInfo; 1916 1917 public UpdatePreviewIconTask(MessageViewAttachmentInfo attachmentInfo) { 1918 super(mTaskTracker); 1919 mContext = getActivity(); 1920 mAttachmentInfo = attachmentInfo; 1921 } 1922 1923 @Override 1924 protected Bitmap doInBackground(Void... params) { 1925 return getPreviewIcon(mContext, mAttachmentInfo); 1926 } 1927 1928 @Override 1929 protected void onSuccess(Bitmap result) { 1930 if (result == null) { 1931 return; 1932 } 1933 mAttachmentInfo.iconView.setImageBitmap(result); 1934 } 1935 } 1936 1937 private boolean shouldShowImagesFor(String senderEmail) { 1938 return Preferences.getPreferences(getActivity()).shouldShowImagesFor(senderEmail); 1939 } 1940 1941 private void setShowImagesForSender() { 1942 makeVisible(UiUtilities.getView(getView(), R.id.always_show_pictures_button), false); 1943 Utility.showToast(getActivity(), R.string.message_view_always_show_pictures_confirmation); 1944 1945 // Force redraw of the container. 1946 updateTabs(mTabFlags); 1947 1948 Address[] fromList = Address.unpack(mMessage.mFrom); 1949 Preferences prefs = Preferences.getPreferences(getActivity()); 1950 for (Address sender : fromList) { 1951 String email = sender.getAddress(); 1952 prefs.setSenderAsTrusted(email); 1953 } 1954 } 1955 1956 public boolean isMessageLoadedForTest() { 1957 return mIsMessageLoadedForTest; 1958 } 1959 1960 public void clearIsMessageLoadedForTest() { 1961 mIsMessageLoadedForTest = true; 1962 } 1963} 1964