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