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