MessageCompose.java revision a740e2935746254b836051069813489cb38be666
1/* 2 * Copyright (C) 2008 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.Email; 21import com.android.email.EmailAddressAdapter; 22import com.android.email.EmailAddressValidator; 23import com.android.email.R; 24import com.android.email.mail.Address; 25import com.android.email.mail.MessagingException; 26import com.android.email.mail.internet.EmailHtmlUtil; 27import com.android.email.mail.internet.MimeUtility; 28import com.android.email.provider.EmailContent; 29import com.android.email.provider.EmailContent.Account; 30import com.android.email.provider.EmailContent.Attachment; 31import com.android.email.provider.EmailContent.Body; 32import com.android.email.provider.EmailContent.BodyColumns; 33import com.android.email.provider.EmailContent.Message; 34import com.android.email.provider.EmailContent.MessageColumns; 35 36import android.app.Activity; 37import android.content.ActivityNotFoundException; 38import android.content.ContentResolver; 39import android.content.ContentValues; 40import android.content.Context; 41import android.content.Intent; 42import android.content.pm.ActivityInfo; 43import android.database.Cursor; 44import android.net.Uri; 45import android.os.AsyncTask; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.Parcelable; 49import android.provider.OpenableColumns; 50import android.text.InputFilter; 51import android.text.SpannableStringBuilder; 52import android.text.Spanned; 53import android.text.TextWatcher; 54import android.text.util.Rfc822Tokenizer; 55import android.util.Log; 56import android.view.Menu; 57import android.view.MenuItem; 58import android.view.View; 59import android.view.Window; 60import android.view.View.OnClickListener; 61import android.view.View.OnFocusChangeListener; 62import android.webkit.WebView; 63import android.widget.Button; 64import android.widget.EditText; 65import android.widget.ImageButton; 66import android.widget.LinearLayout; 67import android.widget.MultiAutoCompleteTextView; 68import android.widget.TextView; 69import android.widget.Toast; 70 71import java.io.UnsupportedEncodingException; 72import java.net.URLDecoder; 73import java.util.ArrayList; 74import java.util.List; 75 76 77public class MessageCompose extends Activity implements OnClickListener, OnFocusChangeListener { 78 private static final String ACTION_REPLY = "com.android.email.intent.action.REPLY"; 79 private static final String ACTION_REPLY_ALL = "com.android.email.intent.action.REPLY_ALL"; 80 private static final String ACTION_FORWARD = "com.android.email.intent.action.FORWARD"; 81 private static final String ACTION_EDIT_DRAFT = "com.android.email.intent.action.EDIT_DRAFT"; 82 83 private static final String EXTRA_ACCOUNT_ID = "account_id"; 84 private static final String EXTRA_MESSAGE_ID = "message_id"; 85 private static final String STATE_KEY_CC_SHOWN = 86 "com.android.email.activity.MessageCompose.ccShown"; 87 private static final String STATE_KEY_BCC_SHOWN = 88 "com.android.email.activity.MessageCompose.bccShown"; 89 private static final String STATE_KEY_QUOTED_TEXT_SHOWN = 90 "com.android.email.activity.MessageCompose.quotedTextShown"; 91 private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = 92 "com.android.email.activity.MessageCompose.stateKeySourceMessageProced"; 93 94 private static final int MSG_PROGRESS_ON = 1; 95 private static final int MSG_PROGRESS_OFF = 2; 96 private static final int MSG_UPDATE_TITLE = 3; 97 private static final int MSG_SKIPPED_ATTACHMENTS = 4; 98 private static final int MSG_DISCARDED_DRAFT = 6; 99 100 private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1; 101 102 private static final String[] ATTACHMENT_META_COLUMNS = { 103 OpenableColumns.DISPLAY_NAME, 104 OpenableColumns.SIZE 105 }; 106 107 private Account mAccount; 108 109 // mDraft is null until the first save, afterwards it contains the last saved version. 110 private Message mDraft; 111 112 // mSource is only set for REPLY, REPLY_ALL and FORWARD, and contains the source message. 113 private Message mSource; 114 115 /** 116 * Indicates that the source message has been processed at least once and should not 117 * be processed on any subsequent loads. This protects us from adding attachments that 118 * have already been added from the restore of the view state. 119 */ 120 private boolean mSourceMessageProcessed = false; 121 122 private MultiAutoCompleteTextView mToView; 123 private MultiAutoCompleteTextView mCcView; 124 private MultiAutoCompleteTextView mBccView; 125 private EditText mSubjectView; 126 private EditText mMessageContentView; 127 private Button mSendButton; 128 private Button mDiscardButton; 129 private Button mSaveButton; 130 private LinearLayout mAttachments; 131 private View mQuotedTextBar; 132 private ImageButton mQuotedTextDelete; 133 private WebView mQuotedText; 134 135 private Controller mController; 136 private Listener mListener = new Listener(); 137 private boolean mDraftNeedsSaving; 138 private AsyncTask mLoadAttachmentsTask; 139 private AsyncTask mSaveMessageTask; 140 private AsyncTask mLoadMessageTask; 141 142 private Handler mHandler = new Handler() { 143 @Override 144 public void handleMessage(android.os.Message msg) { 145 switch (msg.what) { 146 case MSG_PROGRESS_ON: 147 setProgressBarIndeterminateVisibility(true); 148 break; 149 case MSG_PROGRESS_OFF: 150 setProgressBarIndeterminateVisibility(false); 151 break; 152 case MSG_UPDATE_TITLE: 153 updateTitle(); 154 break; 155 case MSG_SKIPPED_ATTACHMENTS: 156 Toast.makeText( 157 MessageCompose.this, 158 getString(R.string.message_compose_attachments_skipped_toast), 159 Toast.LENGTH_LONG).show(); 160 break; 161 default: 162 super.handleMessage(msg); 163 break; 164 } 165 } 166 }; 167 168 /** 169 * Compose a new message using the given account. If account is -1 the default account 170 * will be used. 171 * @param context 172 * @param account 173 */ 174 public static void actionCompose(Context context, long accountId) { 175 try { 176 Intent i = new Intent(context, MessageCompose.class); 177 i.putExtra(EXTRA_ACCOUNT_ID, accountId); 178 context.startActivity(i); 179 } catch (ActivityNotFoundException anfe) { 180 // Swallow it - this is usually a race condition, especially under automated test. 181 // (The message composer might have been disabled) 182 Email.log(anfe.toString()); 183 } 184 } 185 186 /** 187 * Compose a new message as a reply to the given message. If replyAll is true the function 188 * is reply all instead of simply reply. 189 * @param context 190 * @param messageId 191 * @param replyAll 192 */ 193 public static void actionReply(Context context, long messageId, boolean replyAll) { 194 startActivityWithMessage(context, replyAll ? ACTION_REPLY_ALL : ACTION_REPLY, messageId); 195 } 196 197 /** 198 * Compose a new message as a forward of the given message. 199 * @param context 200 * @param messageId 201 */ 202 public static void actionForward(Context context, long messageId) { 203 startActivityWithMessage(context, ACTION_FORWARD, messageId); 204 } 205 206 /** 207 * Continue composition of the given message. This action modifies the way this Activity 208 * handles certain actions. 209 * Save will attempt to replace the message in the given folder with the updated version. 210 * Discard will delete the message from the given folder. 211 * @param context 212 * @param messageId the message id. 213 */ 214 public static void actionEditDraft(Context context, long messageId) { 215 startActivityWithMessage(context, ACTION_EDIT_DRAFT, messageId); 216 } 217 218 private static void startActivityWithMessage(Context context, String action, long messageId) { 219 Intent i = new Intent(context, MessageCompose.class); 220 i.putExtra(EXTRA_MESSAGE_ID, messageId); 221 i.setAction(action); 222 context.startActivity(i); 223 } 224 225 private void setAccount(Intent intent) { 226 long accountId = intent.getLongExtra(EXTRA_ACCOUNT_ID, -1); 227 if (accountId == -1) { 228 accountId = Account.getDefaultAccountId(this); 229 } 230 if (accountId == -1) { 231 // There are no accounts set up. This should not have happened. Prompt the 232 // user to set up an account as an acceptable bailout. 233 AccountFolderList.actionShowAccounts(this); 234 finish(); 235 } else { 236 mAccount = Account.restoreAccountWithId(this, accountId); 237 } 238 } 239 240 @Override 241 public void onCreate(Bundle savedInstanceState) { 242 super.onCreate(savedInstanceState); 243 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 244 setContentView(R.layout.message_compose); 245 mController = Controller.getInstance(getApplication()); 246 initViews(); 247 248 if (savedInstanceState != null) { 249 /* 250 * This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState 251 */ 252 mSourceMessageProcessed = 253 savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); 254 } 255 256 Intent intent = getIntent(); 257 final String action = intent.getAction(); 258 259 // Handle the various intents that launch the message composer 260 if (Intent.ACTION_VIEW.equals(action) 261 || Intent.ACTION_SENDTO.equals(action) 262 || Intent.ACTION_SEND.equals(action) 263 || Intent.ACTION_SEND_MULTIPLE.equals(action)) { 264 setAccount(intent); 265 // Use the fields found in the Intent to prefill as much of the message as possible 266 initFromIntent(intent); 267 } else { 268 // Otherwise, handle the internal cases (Message Composer invoked from within app) 269 long messageId = intent.getLongExtra(EXTRA_MESSAGE_ID, -1); 270 if (messageId != -1) { 271 mLoadMessageTask = new LoadMessageTask().execute(messageId); 272 } else { 273 setAccount(intent); 274 } 275 if (ACTION_EDIT_DRAFT.equals(action) && messageId != -1) { 276 mLoadAttachmentsTask = new AsyncTask<Long, Void, Attachment[]>() { 277 @Override 278 protected Attachment[] doInBackground(Long... messageIds) { 279 return Attachment.restoreAttachmentsWithMessageId(MessageCompose.this, 280 messageIds[0]); 281 } 282 @Override 283 protected void onPostExecute(Attachment[] attachments) { 284 for (Attachment attachment : attachments) { 285 addAttachment(attachment); 286 } 287 } 288 }.execute(messageId); 289 } 290 } 291 292 if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) || 293 ACTION_FORWARD.equals(action) || ACTION_EDIT_DRAFT.equals(action)) { 294 /* 295 * If we need to load the message we add ourself as a message listener here 296 * so we can kick it off. Normally we add in onResume but we don't 297 * want to reload the message every time the activity is resumed. 298 * There is no harm in adding twice. 299 */ 300 // TODO: signal the controller to load the message 301 } 302 updateTitle(); 303 } 304 305 @Override 306 public void onResume() { 307 super.onResume(); 308 mController.addResultCallback(mListener); 309 } 310 311 @Override 312 public void onPause() { 313 super.onPause(); 314 saveIfNeeded(); 315 mController.removeResultCallback(mListener); 316 } 317 318 private static void cancelTask(AsyncTask<?, ?, ?> task) { 319 if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) { 320 task.cancel(true); 321 } 322 } 323 324 /** 325 * We override onDestroy to make sure that the WebView gets explicitly destroyed. 326 * Otherwise it can leak native references. 327 */ 328 @Override 329 public void onDestroy() { 330 super.onDestroy(); 331 mQuotedText.destroy(); 332 mQuotedText = null; 333 cancelTask(mLoadAttachmentsTask); 334 mLoadAttachmentsTask = null; 335 cancelTask(mLoadMessageTask); 336 mLoadMessageTask = null; 337 // don't cancel mSaveMessageTask, let it do its job to the end. 338 // cancelTask(mSaveMessageTask); 339 } 340 341 /** 342 * The framework handles most of the fields, but we need to handle stuff that we 343 * dynamically show and hide: 344 * Cc field, 345 * Bcc field, 346 * Quoted text, 347 */ 348 @Override 349 protected void onSaveInstanceState(Bundle outState) { 350 super.onSaveInstanceState(outState); 351 saveIfNeeded(); 352 outState.putBoolean(STATE_KEY_CC_SHOWN, mCcView.getVisibility() == View.VISIBLE); 353 outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccView.getVisibility() == View.VISIBLE); 354 outState.putBoolean(STATE_KEY_QUOTED_TEXT_SHOWN, 355 mQuotedTextBar.getVisibility() == View.VISIBLE); 356 outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed); 357 } 358 359 @Override 360 protected void onRestoreInstanceState(Bundle savedInstanceState) { 361 super.onRestoreInstanceState(savedInstanceState); 362 mCcView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? 363 View.VISIBLE : View.GONE); 364 mBccView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_BCC_SHOWN) ? 365 View.VISIBLE : View.GONE); 366 mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? 367 View.VISIBLE : View.GONE); 368 mQuotedText.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? 369 View.VISIBLE : View.GONE); 370 mDraftNeedsSaving = false; 371 } 372 373 private void initViews() { 374 mToView = (MultiAutoCompleteTextView)findViewById(R.id.to); 375 mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc); 376 mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc); 377 mSubjectView = (EditText)findViewById(R.id.subject); 378 mMessageContentView = (EditText)findViewById(R.id.message_content); 379 mSendButton = (Button)findViewById(R.id.send); 380 mDiscardButton = (Button)findViewById(R.id.discard); 381 mSaveButton = (Button)findViewById(R.id.save); 382 mAttachments = (LinearLayout)findViewById(R.id.attachments); 383 mQuotedTextBar = findViewById(R.id.quoted_text_bar); 384 mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete); 385 mQuotedText = (WebView)findViewById(R.id.quoted_text); 386 387 TextWatcher watcher = new TextWatcher() { 388 public void beforeTextChanged(CharSequence s, int start, 389 int before, int after) { } 390 391 public void onTextChanged(CharSequence s, int start, 392 int before, int count) { 393 mDraftNeedsSaving = true; 394 } 395 396 public void afterTextChanged(android.text.Editable s) { } 397 }; 398 399 /** 400 * Implements special address cleanup rules: 401 * The first space key entry following an "@" symbol that is followed by any combination 402 * of letters and symbols, including one+ dots and zero commas, should insert an extra 403 * comma (followed by the space). 404 */ 405 InputFilter recipientFilter = new InputFilter() { 406 407 public CharSequence filter(CharSequence source, int start, int end, Spanned dest, 408 int dstart, int dend) { 409 410 // quick check - did they enter a single space? 411 if (end-start != 1 || source.charAt(start) != ' ') { 412 return null; 413 } 414 415 // determine if the characters before the new space fit the pattern 416 // follow backwards and see if we find a comma, dot, or @ 417 int scanBack = dstart; 418 boolean dotFound = false; 419 while (scanBack > 0) { 420 char c = dest.charAt(--scanBack); 421 switch (c) { 422 case '.': 423 dotFound = true; // one or more dots are req'd 424 break; 425 case ',': 426 return null; 427 case '@': 428 if (!dotFound) { 429 return null; 430 } 431 432 // we have found a comma-insert case. now just do it 433 // in the least expensive way we can. 434 if (source instanceof Spanned) { 435 SpannableStringBuilder sb = new SpannableStringBuilder(","); 436 sb.append(source); 437 return sb; 438 } else { 439 return ", "; 440 } 441 default: 442 // just keep going 443 } 444 } 445 446 // no termination cases were found, so don't edit the input 447 return null; 448 } 449 }; 450 InputFilter[] recipientFilters = new InputFilter[] { recipientFilter }; 451 452 mToView.addTextChangedListener(watcher); 453 mCcView.addTextChangedListener(watcher); 454 mBccView.addTextChangedListener(watcher); 455 mSubjectView.addTextChangedListener(watcher); 456 mMessageContentView.addTextChangedListener(watcher); 457 458 // NOTE: assumes no other filters are set 459 mToView.setFilters(recipientFilters); 460 mCcView.setFilters(recipientFilters); 461 mBccView.setFilters(recipientFilters); 462 463 /* 464 * We set this to invisible by default. Other methods will turn it back on if it's 465 * needed. 466 */ 467 mQuotedTextBar.setVisibility(View.GONE); 468 mQuotedText.setVisibility(View.GONE); 469 470 mQuotedTextDelete.setOnClickListener(this); 471 472 EmailAddressAdapter addressAdapter = new EmailAddressAdapter(this); 473 EmailAddressValidator addressValidator = new EmailAddressValidator(); 474 475 mToView.setAdapter(addressAdapter); 476 mToView.setTokenizer(new Rfc822Tokenizer()); 477 mToView.setValidator(addressValidator); 478 479 mCcView.setAdapter(addressAdapter); 480 mCcView.setTokenizer(new Rfc822Tokenizer()); 481 mCcView.setValidator(addressValidator); 482 483 mBccView.setAdapter(addressAdapter); 484 mBccView.setTokenizer(new Rfc822Tokenizer()); 485 mBccView.setValidator(addressValidator); 486 487 mSendButton.setOnClickListener(this); 488 mDiscardButton.setOnClickListener(this); 489 mSaveButton.setOnClickListener(this); 490 491 mSubjectView.setOnFocusChangeListener(this); 492 } 493 494 // TODO: is there any way to unify this with MessageView.LoadMessageTask? 495 private class LoadMessageTask extends AsyncTask<Long, Void, Object[]> { 496 @Override 497 protected Object[] doInBackground(Long... messageIds) { 498 Message message = Message.restoreMessageWithId(MessageCompose.this, messageIds[0]); 499 long accountId = message.mAccountKey; 500 Account account = Account.restoreAccountWithId(MessageCompose.this, accountId); 501 Body body = Body.restoreBodyWithMessageId(MessageCompose.this, message.mId); 502 message.mHtml = body.mHtmlContent; 503 message.mText = body.mTextContent; 504 return new Object[]{message, account}; 505 } 506 507 @Override 508 protected void onPostExecute(Object[] messageAndAccount) { 509 final Message message = (Message) messageAndAccount[0]; 510 final Account account = (Account) messageAndAccount[1]; 511 final String action = getIntent().getAction(); 512 if (ACTION_EDIT_DRAFT.equals(action)) { 513 mDraft = message; 514 } else if (ACTION_REPLY.equals(action) 515 || ACTION_REPLY_ALL.equals(action) 516 || ACTION_FORWARD.equals(action)) { 517 mSource = message; 518 } else if (Email.LOGD) { 519 Email.log("Action " + action + " has unexpected EXTRA_MESSAGE_ID"); 520 } 521 522 mAccount = account; 523 // Make sure we only do this once (otherwise we'll duplicate addresses!) 524 if (!mSourceMessageProcessed) { 525 processSourceMessage(message, mAccount); 526 } 527 } 528 } 529 530 private void updateTitle() { 531 if (mSubjectView.getText().length() == 0) { 532 setTitle(R.string.compose_title); 533 } else { 534 setTitle(mSubjectView.getText().toString()); 535 } 536 } 537 538 public void onFocusChange(View view, boolean focused) { 539 if (!focused) { 540 updateTitle(); 541 } 542 } 543 544 private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) { 545 if (addresses == null) { 546 return; 547 } 548 for (Address address : addresses) { 549 addAddress(view, address.toString()); 550 } 551 } 552 553 private void addAddresses(MultiAutoCompleteTextView view, String[] addresses) { 554 if (addresses == null) { 555 return; 556 } 557 for (String oneAddress : addresses) { 558 addAddress(view, oneAddress); 559 } 560 } 561 562 private void addAddress(MultiAutoCompleteTextView view, String address) { 563 view.append(address + ", "); 564 } 565 566 private String getPackedAddresses(TextView view) { 567 Address[] addresses = Address.parse(view.getText().toString().trim()); 568 return Address.pack(addresses); 569 } 570 571 private Address[] getAddresses(TextView view) { 572 Address[] addresses = Address.parse(view.getText().toString().trim()); 573 return addresses; 574 } 575 576 private ContentValues getUpdateContentValues(Message message) { 577 ContentValues values = new ContentValues(); 578 values.put(MessageColumns.TIMESTAMP, message.mTimeStamp); 579 values.put(MessageColumns.FROM_LIST, message.mFrom); 580 values.put(MessageColumns.TO_LIST, message.mTo); 581 values.put(MessageColumns.CC_LIST, message.mCc); 582 values.put(MessageColumns.BCC_LIST, message.mBcc); 583 values.put(MessageColumns.SUBJECT, message.mSubject); 584 values.put(MessageColumns.DISPLAY_NAME, message.mDisplayName); 585 values.put(MessageColumns.FLAG_LOADED, message.mFlagLoaded); 586 values.put(MessageColumns.FLAG_ATTACHMENT, message.mFlagAttachment); 587 values.put(MessageColumns.FLAGS, message.mFlags); 588 return values; 589 } 590 591 /* 592 * Computes a short string indicating the destination of the message based on To, Cc, Bcc. 593 * If only one address appears, returns the friendly form of that address. 594 * Otherwise returns the friendly form of the first address appended with "and N others". 595 */ 596 private String makeDisplayName(String packedTo, String packedCc, String packedBcc) { 597 Address first = null; 598 int nRecipients = 0; 599 for (String packed: new String[] {packedTo, packedCc, packedBcc}) { 600 Address[] addresses = Address.unpack(packed); 601 nRecipients += addresses.length; 602 if (first == null && addresses.length > 0) { 603 first = addresses[0]; 604 } 605 } 606 if (nRecipients == 0) { 607 return ""; 608 } 609 String friendly = first.toFriendly(); 610 if (nRecipients == 1) { 611 return friendly; 612 } 613 return this.getString(R.string.message_compose_display_name, friendly, nRecipients - 1); 614 } 615 616 /** 617 * @param message The message to be updated. 618 * @param account the account (used to obtain From: address). 619 * @param bodyText the body text. 620 */ 621 private void updateMessage(Message message, Account account, boolean hasAttachments) { 622 message.mTimeStamp = System.currentTimeMillis(); 623 message.mFrom = new Address(account.getEmailAddress(), account.getSenderName()).pack(); 624 message.mTo = getPackedAddresses(mToView); 625 message.mCc = getPackedAddresses(mCcView); 626 message.mBcc = getPackedAddresses(mBccView); 627 message.mSubject = mSubjectView.getText().toString(); 628 message.mText = mMessageContentView.getText().toString(); 629 message.mAccountKey = account.mId; 630 message.mDisplayName = makeDisplayName(message.mTo, message.mCc, message.mBcc); 631 message.mFlagLoaded = Message.FLAG_LOADED_COMPLETE; 632 message.mFlagAttachment = hasAttachments; 633 String action = getIntent().getAction(); 634 // Use the Intent to set flags saying this message is a reply or a forward and save the 635 // unique id of the source message 636 if (mSource != null && mQuotedTextBar.getVisibility() == View.VISIBLE) { 637 if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action) 638 || ACTION_FORWARD.equals(action)) { 639 message.mSourceKey = mSource.mId; 640 // Get the body of the source message here 641 // Note that the following commented line will be useful when we use HTML in replies 642 //message.mHtmlReply = mSource.mHtml; 643 message.mTextReply = mSource.mText; 644 } 645 if (ACTION_FORWARD.equals(action)) { 646 message.mFlags |= Message.FLAG_TYPE_FORWARD; 647 } else { 648 message.mFlags |= Message.FLAG_TYPE_REPLY; 649 } 650 } 651 } 652 653 private Attachment[] getAttachmentsFromUI() { 654 int count = mAttachments.getChildCount(); 655 Attachment[] attachments = new Attachment[count]; 656 for (int i = 0; i < count; ++i) { 657 attachments[i] = (Attachment) mAttachments.getChildAt(i).getTag(); 658 } 659 return attachments; 660 } 661 662 /** 663 * Send or save a message: 664 * - out of the UI thread 665 * - write to Drafts 666 * - if send, invoke Controller.sendMessage() 667 * - when operation is complete, display toast 668 */ 669 private void sendOrSaveMessage(final boolean send) { 670 if (mDraft == null) { 671 mDraft = new Message(); 672 } 673 final Attachment[] attachments = getAttachmentsFromUI(); 674 updateMessage(mDraft, mAccount, attachments.length > 0); 675 676 mSaveMessageTask = new AsyncTask<Void, Void, Void>() { 677 @Override 678 protected Void doInBackground(Void... params) { 679 synchronized (mDraft) { 680 if (mDraft.isSaved()) { 681 mDraft.update(MessageCompose.this, getUpdateContentValues(mDraft)); 682 ContentValues values = new ContentValues(); 683 values.put(BodyColumns.TEXT_CONTENT, mDraft.mText); 684 values.put(BodyColumns.TEXT_REPLY, mDraft.mTextReply); 685 values.put(BodyColumns.HTML_REPLY, mDraft.mHtmlReply); 686 Body.updateBodyWithMessageId(MessageCompose.this, mDraft.mId, values); 687 } else { 688 // mDraft.mId is set upon return of saveToMailbox() 689 mController.saveToMailbox(mDraft, EmailContent.Mailbox.TYPE_DRAFTS); 690 } 691 692 // TODO: remove from DB the attachments that were removed from UI 693 for (Attachment attachment : attachments) { 694 if (!attachment.isSaved()) { 695 // this attachment is new so save it to DB. 696 attachment.mMessageKey = mDraft.mId; 697 attachment.save(MessageCompose.this); 698 } 699 } 700 701 if (send) { 702 mController.sendMessage(mDraft.mId, mDraft.mAccountKey); 703 } 704 return null; 705 } 706 } 707 708 @Override 709 protected void onPostExecute(Void dummy) { 710 // Don't display the toast if the user is just changing the orientation 711 if (!send && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) { 712 Toast.makeText(MessageCompose.this, R.string.message_saved_toast, 713 Toast.LENGTH_LONG).show(); 714 } 715 } 716 }.execute(); 717 } 718 719 private void saveIfNeeded() { 720 if (!mDraftNeedsSaving) { 721 return; 722 } 723 mDraftNeedsSaving = false; 724 sendOrSaveMessage(false); 725 } 726 727 /** 728 * Checks whether all the email addresses listed in TO, CC, BCC are valid. 729 */ 730 /* package */ boolean isAddressAllValid() { 731 for (TextView view : new TextView[]{mToView, mCcView, mBccView}) { 732 String addresses = view.getText().toString().trim(); 733 if (!Address.isAllValid(addresses)) { 734 view.setError(getString(R.string.message_compose_error_invalid_email)); 735 return false; 736 } 737 } 738 return true; 739 } 740 741 private void onSend() { 742 if (!isAddressAllValid()) { 743 Toast.makeText(this, getString(R.string.message_compose_error_invalid_email), 744 Toast.LENGTH_LONG).show(); 745 } else if (getAddresses(mToView).length == 0 && 746 getAddresses(mCcView).length == 0 && 747 getAddresses(mBccView).length == 0) { 748 mToView.setError(getString(R.string.message_compose_error_no_recipients)); 749 Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), 750 Toast.LENGTH_LONG).show(); 751 } else { 752 sendOrSaveMessage(true); 753 mDraftNeedsSaving = false; 754 finish(); 755 } 756 } 757 758 private void onDiscard() { 759 if (mDraft != null) { 760 mController.deleteMessage(mDraft.mId, mDraft.mAccountKey); 761 } 762 Toast.makeText(this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); 763 mDraftNeedsSaving = false; 764 finish(); 765 } 766 767 private void onSave() { 768 saveIfNeeded(); 769 finish(); 770 } 771 772 private void onAddCcBcc() { 773 mCcView.setVisibility(View.VISIBLE); 774 mBccView.setVisibility(View.VISIBLE); 775 } 776 777 /** 778 * Kick off a picker for whatever kind of MIME types we'll accept and let Android take over. 779 */ 780 private void onAddAttachment() { 781 Intent i = new Intent(Intent.ACTION_GET_CONTENT); 782 i.addCategory(Intent.CATEGORY_OPENABLE); 783 i.setType(Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES[0]); 784 startActivityForResult( 785 Intent.createChooser(i, getString(R.string.choose_attachment_dialog_title)), 786 ACTIVITY_REQUEST_PICK_ATTACHMENT); 787 } 788 789 private Attachment loadAttachmentInfo(Uri uri) { 790 int size = -1; 791 String name = null; 792 ContentResolver contentResolver = getContentResolver(); 793 Cursor metadataCursor = contentResolver.query(uri, 794 ATTACHMENT_META_COLUMNS, null, null, null); 795 if (metadataCursor != null) { 796 try { 797 if (metadataCursor.moveToFirst()) { 798 name = metadataCursor.getString(0); 799 size = metadataCursor.getInt(1); 800 } 801 } finally { 802 metadataCursor.close(); 803 } 804 } 805 if (name == null) { 806 name = uri.getLastPathSegment(); 807 } 808 809 String contentType = contentResolver.getType(uri); 810 if (contentType == null) { 811 contentType = ""; 812 } 813 814 Attachment attachment = new Attachment(); 815 attachment.mFileName = name; 816 attachment.mContentUri = uri.toString(); 817 attachment.mSize = size; 818 attachment.mMimeType = contentType; 819 return attachment; 820 } 821 822 private void addAttachment(Attachment attachment) { 823 // Before attaching the attachment, make sure it meets any other pre-attach criteria 824 if (attachment.mSize > Email.MAX_ATTACHMENT_UPLOAD_SIZE) { 825 Toast.makeText(this, R.string.message_compose_attachment_size, Toast.LENGTH_LONG) 826 .show(); 827 return; 828 } 829 830 View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, 831 mAttachments, false); 832 TextView nameView = (TextView)view.findViewById(R.id.attachment_name); 833 ImageButton delete = (ImageButton)view.findViewById(R.id.attachment_delete); 834 nameView.setText(attachment.mFileName); 835 delete.setOnClickListener(this); 836 delete.setTag(view); 837 view.setTag(attachment); 838 mAttachments.addView(view); 839 } 840 841 private void addAttachment(Uri uri) { 842 addAttachment(loadAttachmentInfo(uri)); 843 } 844 845 @Override 846 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 847 if (data == null) { 848 return; 849 } 850 addAttachment(data.getData()); 851 mDraftNeedsSaving = true; 852 } 853 854 public void onClick(View view) { 855 switch (view.getId()) { 856 case R.id.send: 857 onSend(); 858 break; 859 case R.id.save: 860 onSave(); 861 break; 862 case R.id.discard: 863 onDiscard(); 864 break; 865 case R.id.attachment_delete: 866 /* 867 * The view is the delete button, and we have previously set the tag of 868 * the delete button to the view that owns it. We don't use parent because the 869 * view is very complex and could change in the future. 870 */ 871 mAttachments.removeView((View) view.getTag()); 872 mDraftNeedsSaving = true; 873 break; 874 case R.id.quoted_text_delete: 875 mQuotedTextBar.setVisibility(View.GONE); 876 mQuotedText.setVisibility(View.GONE); 877 mDraftNeedsSaving = true; 878 break; 879 } 880 } 881 882 @Override 883 public boolean onOptionsItemSelected(MenuItem item) { 884 switch (item.getItemId()) { 885 case R.id.send: 886 onSend(); 887 break; 888 case R.id.save: 889 onSave(); 890 break; 891 case R.id.discard: 892 onDiscard(); 893 break; 894 case R.id.add_cc_bcc: 895 onAddCcBcc(); 896 break; 897 case R.id.add_attachment: 898 onAddAttachment(); 899 break; 900 default: 901 return super.onOptionsItemSelected(item); 902 } 903 return true; 904 } 905 906 @Override 907 public boolean onCreateOptionsMenu(Menu menu) { 908 super.onCreateOptionsMenu(menu); 909 getMenuInflater().inflate(R.menu.message_compose_option, menu); 910 return true; 911 } 912 913 /** 914 * Returns true if all attachments were able to be attached, otherwise returns false. 915 */ 916// private boolean loadAttachments(Part part, int depth) throws MessagingException { 917// if (part.getBody() instanceof Multipart) { 918// Multipart mp = (Multipart) part.getBody(); 919// boolean ret = true; 920// for (int i = 0, count = mp.getCount(); i < count; i++) { 921// if (!loadAttachments(mp.getBodyPart(i), depth + 1)) { 922// ret = false; 923// } 924// } 925// return ret; 926// } else { 927// String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); 928// String name = MimeUtility.getHeaderParameter(contentType, "name"); 929// if (name != null) { 930// Body body = part.getBody(); 931// if (body != null && body instanceof LocalAttachmentBody) { 932// final Uri uri = ((LocalAttachmentBody) body).getContentUri(); 933// mHandler.post(new Runnable() { 934// public void run() { 935// addAttachment(uri); 936// } 937// }); 938// } 939// else { 940// return false; 941// } 942// } 943// return true; 944// } 945// } 946 947 /** 948 * Fill all the widgets with the content found in the Intent Extra, if any. 949 * 950 * Note that we don't actually check the intent action (typically VIEW, SENDTO, or SEND). 951 * There is enough overlap in the definitions that it makes more sense to simply check for 952 * all available data and use as much of it as possible. 953 * 954 * With one exception: EXTRA_STREAM is defined as only valid for ACTION_SEND. 955 * 956 * @param intent the launch intent 957 */ 958 /* package */ void initFromIntent(Intent intent) { 959 960 // First, add values stored in top-level extras 961 962 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); 963 if (extraStrings != null) { 964 addAddresses(mToView, extraStrings); 965 } 966 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC); 967 if (extraStrings != null) { 968 addAddresses(mCcView, extraStrings); 969 } 970 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC); 971 if (extraStrings != null) { 972 addAddresses(mBccView, extraStrings); 973 } 974 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT); 975 if (extraString != null) { 976 mSubjectView.setText(extraString); 977 } 978 979 // Next, if we were invoked with a URI, try to interpret it 980 // We'll take two courses here. If it's mailto:, there is a specific set of rules 981 // that define various optional fields. However, for any other scheme, we'll simply 982 // take the entire scheme-specific part and interpret it as a possible list of addresses. 983 984 final Uri dataUri = intent.getData(); 985 if (dataUri != null) { 986 if ("mailto".equals(dataUri.getScheme())) { 987 initializeFromMailTo(dataUri.toString()); 988 } else { 989 String toText = dataUri.getSchemeSpecificPart(); 990 if (toText != null) { 991 addAddresses(mToView, toText.split(",")); 992 } 993 } 994 } 995 996 // Next, fill in the plaintext (note, this will override mailto:?body=) 997 998 CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); 999 if (text != null) { 1000 mMessageContentView.setText(text); 1001 } 1002 1003 // Next, convert EXTRA_STREAM into an attachment 1004 1005 if (Intent.ACTION_SEND.equals(intent.getAction()) && intent.hasExtra(Intent.EXTRA_STREAM)) { 1006 String type = intent.getType(); 1007 Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); 1008 if (stream != null && type != null) { 1009 if (MimeUtility.mimeTypeMatches(type, Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) { 1010 addAttachment(stream); 1011 } 1012 } 1013 } 1014 1015 if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction()) 1016 && intent.hasExtra(Intent.EXTRA_STREAM)) { 1017 ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); 1018 if (list != null) { 1019 for (Parcelable parcelable : list) { 1020 Uri uri = (Uri) parcelable; 1021 if (uri != null) { 1022 Attachment attachment = loadAttachmentInfo(uri); 1023 if (MimeUtility.mimeTypeMatches(attachment.mMimeType, 1024 Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) { 1025 addAttachment(attachment); 1026 } 1027 } 1028 } 1029 } 1030 } 1031 1032 // Finally - expose fields that were filled in but are normally hidden, and set focus 1033 1034 if (mCcView.length() > 0) { 1035 mCcView.setVisibility(View.VISIBLE); 1036 } 1037 if (mBccView.length() > 0) { 1038 mBccView.setVisibility(View.VISIBLE); 1039 } 1040 setNewMessageFocus(); 1041 mDraftNeedsSaving = false; 1042 } 1043 1044 /** 1045 * When we are launched with an intent that includes a mailto: URI, we can actually 1046 * gather quite a few of our message fields from it. 1047 * 1048 * @mailToString the href (which must start with "mailto:"). 1049 */ 1050 private void initializeFromMailTo(String mailToString) { 1051 1052 // Chop up everything between mailto: and ? to find recipients 1053 int index = mailToString.indexOf("?"); 1054 int length = "mailto".length() + 1; 1055 String to; 1056 try { 1057 // Extract the recipient after mailto: 1058 if (index == -1) { 1059 to = decode(mailToString.substring(length)); 1060 } else { 1061 to = decode(mailToString.substring(length, index)); 1062 } 1063 addAddresses(mToView, to.split(" ,")); 1064 } catch (UnsupportedEncodingException e) { 1065 Log.e(Email.LOG_TAG, e.getMessage() + " while decoding '" + mailToString + "'"); 1066 } 1067 1068 // Extract the other parameters 1069 1070 // We need to disguise this string as a URI in order to parse it 1071 Uri uri = Uri.parse("foo://" + mailToString); 1072 1073 List<String> cc = uri.getQueryParameters("cc"); 1074 addAddresses(mCcView, cc.toArray(new String[cc.size()])); 1075 1076 List<String> otherTo = uri.getQueryParameters("to"); 1077 addAddresses(mCcView, otherTo.toArray(new String[otherTo.size()])); 1078 1079 List<String> bcc = uri.getQueryParameters("bcc"); 1080 addAddresses(mBccView, bcc.toArray(new String[bcc.size()])); 1081 1082 List<String> subject = uri.getQueryParameters("subject"); 1083 if (subject.size() > 0) { 1084 mSubjectView.setText(subject.get(0)); 1085 } 1086 1087 List<String> body = uri.getQueryParameters("body"); 1088 if (body.size() > 0) { 1089 mMessageContentView.setText(body.get(0)); 1090 } 1091 } 1092 1093 private String decode(String s) throws UnsupportedEncodingException { 1094 return URLDecoder.decode(s, "UTF-8"); 1095 } 1096 1097 // used by processSourceMessage() 1098 private void displayQuotedText(Message message) { 1099 boolean plainTextFlag = message.mHtml == null; 1100 String text = plainTextFlag ? message.mText : message.mHtml; 1101 if (text != null) { 1102 text = plainTextFlag ? EmailHtmlUtil.escapeCharacterToDisplay(text) : text; 1103 // TODO: re-enable EmailHtmlUtil.resolveInlineImage() for HTML 1104 // EmailHtmlUtil.resolveInlineImage(getContentResolver(), mAccount, 1105 // text, message, 0); 1106 mQuotedTextBar.setVisibility(View.VISIBLE); 1107 mQuotedText.setVisibility(View.VISIBLE); 1108 mQuotedText.loadDataWithBaseURL("email://", text, "text/html", 1109 "utf-8", null); 1110 } 1111 } 1112 1113 /** 1114 * Given a packed address String, the address of our sending account, a view, and a list of 1115 * addressees already added to other addressing views, adds unique addressees that don't 1116 * match our address to the passed in view 1117 */ 1118 private boolean safeAddAddresses(String addrs, String ourAddress, 1119 MultiAutoCompleteTextView view, ArrayList<Address> addrList) { 1120 boolean added = false; 1121 for (Address address : Address.unpack(addrs)) { 1122 // Don't send to ourselves or already-included addresses 1123 if (!address.getAddress().equalsIgnoreCase(ourAddress) && !addrList.contains(address)) { 1124 addrList.add(address); 1125 addAddress(view, address.toString()); 1126 added = true; 1127 } 1128 } 1129 return added; 1130 } 1131 1132 /** 1133 * Set up the to and cc views properly for the "reply" and "replyAll" cases. What's important 1134 * is that we not 1) send to ourselves, and 2) duplicate addressees. 1135 * @param message the message we're replying to 1136 * @param account the account we're sending from 1137 * @param toView the "To" view 1138 * @param ccView the "Cc" view 1139 * @param replyAll whether this is a replyAll (vs a reply) 1140 */ 1141 /*package*/ void setupAddressViews(Message message, Account account, 1142 MultiAutoCompleteTextView toView, MultiAutoCompleteTextView ccView, boolean replyAll) { 1143 /* 1144 * If a reply-to was included with the message use that, otherwise use the from 1145 * or sender address. 1146 */ 1147 Address[] replyToAddresses = Address.unpack(message.mReplyTo); 1148 if (replyToAddresses.length == 0) { 1149 replyToAddresses = Address.unpack(message.mFrom); 1150 } 1151 addAddresses(mToView, replyToAddresses); 1152 1153 if (replyAll) { 1154 // Keep a running list of addresses we're sending to 1155 ArrayList<Address> allAddresses = new ArrayList<Address>(); 1156 String ourAddress = account.mEmailAddress; 1157 1158 for (Address address: replyToAddresses) { 1159 allAddresses.add(address); 1160 } 1161 1162 safeAddAddresses(message.mTo, ourAddress, mToView, allAddresses); 1163 if (safeAddAddresses(message.mCc, ourAddress, mCcView, allAddresses)) { 1164 mCcView.setVisibility(View.VISIBLE); 1165 } 1166 } 1167 } 1168 1169 /** 1170 * Pull out the parts of the now loaded source message and apply them to the new message 1171 * depending on the type of message being composed. 1172 * @param message 1173 */ 1174 /* package */ 1175 void processSourceMessage(Message message, Account account) { 1176 final String action = getIntent().getAction(); 1177 mDraftNeedsSaving = true; 1178 final String subject = message.mSubject; 1179 if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)) { 1180 setupAddressViews(message, account, mToView, mCcView, ACTION_REPLY_ALL.equals(action)); 1181 1182 if (subject != null && !subject.toLowerCase().startsWith("re:")) { 1183 mSubjectView.setText("Re: " + subject); 1184 } else { 1185 mSubjectView.setText(subject); 1186 } 1187 1188 displayQuotedText(message); 1189 } else if (ACTION_FORWARD.equals(action)) { 1190 mSubjectView.setText(subject != null && !subject.toLowerCase().startsWith("fwd:") ? 1191 "Fwd: " + subject : subject); 1192 displayQuotedText(message); 1193 if (!mSourceMessageProcessed) { 1194 // TODO: re-enable loadAttachments below 1195// if (!loadAttachments(message, 0)) { 1196// mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS); 1197// } 1198 } 1199 } else if (ACTION_EDIT_DRAFT.equals(action)) { 1200 mSubjectView.setText(subject); 1201 addAddresses(mToView, Address.unpack(message.mTo)); 1202 Address[] cc = Address.unpack(message.mCc); 1203 if (cc.length > 0) { 1204 addAddresses(mCcView, cc); 1205 mCcView.setVisibility(View.VISIBLE); 1206 } 1207 Address[] bcc = Address.unpack(message.mBcc); 1208 if (bcc.length > 0) { 1209 addAddresses(mBccView, bcc); 1210 mBccView.setVisibility(View.VISIBLE); 1211 } 1212 1213 // TODO: why not the same text handling as in displayQuotedText() ? 1214 mMessageContentView.setText(message.mText); 1215 1216 if (!mSourceMessageProcessed) { 1217 // TODO: re-enable loadAttachments 1218 // loadAttachments(message, 0); 1219 } 1220 mDraftNeedsSaving = false; 1221 } 1222 setNewMessageFocus(); 1223 mSourceMessageProcessed = true; 1224 } 1225 1226 /** 1227 * In order to accelerate typing, position the cursor in the first empty field, 1228 * or at the end of the body composition field if none are empty. Typically, this will 1229 * play out as follows: 1230 * Reply / Reply All - put cursor in the empty message body 1231 * Forward - put cursor in the empty To field 1232 * Edit Draft - put cursor in whatever field still needs entry 1233 */ 1234 private void setNewMessageFocus() { 1235 if (mToView.length() == 0) { 1236 mToView.requestFocus(); 1237 } else if (mSubjectView.length() == 0) { 1238 mSubjectView.requestFocus(); 1239 } else { 1240 mMessageContentView.requestFocus(); 1241 // when selecting the message content, explicitly move IP to the end, so you can 1242 // quickly resume typing into a draft 1243 int selection = mMessageContentView.length(); 1244 mMessageContentView.setSelection(selection, selection); 1245 } 1246 } 1247 1248 class Listener implements Controller.Result { 1249 public void updateMailboxListCallback(MessagingException result, long accountId, 1250 int progress) { 1251 } 1252 1253 public void updateMailboxCallback(MessagingException result, long accountId, 1254 long mailboxId, int progress, int numNewMessages) { 1255 if (result != null || progress == 100) { 1256 Email.updateMailboxRefreshTime(mailboxId); 1257 } 1258 } 1259 1260 public void loadMessageForViewCallback(MessagingException result, long messageId, 1261 int progress) { 1262 } 1263 1264 public void loadAttachmentCallback(MessagingException result, long messageId, 1265 long attachmentId, int progress) { 1266 } 1267 1268 public void serviceCheckMailCallback(MessagingException result, long accountId, 1269 long mailboxId, int progress, long tag) { 1270 } 1271 1272 public void sendMailCallback(MessagingException result, long accountId, long messageId, 1273 int progress) { 1274 } 1275 } 1276 1277// class Listener extends MessagingListener { 1278// @Override 1279// public void loadMessageForViewStarted(Account account, String folder, 1280// String uid) { 1281// mHandler.sendEmptyMessage(MSG_PROGRESS_ON); 1282// } 1283 1284// @Override 1285// public void loadMessageForViewFinished(Account account, String folder, 1286// String uid, Message message) { 1287// mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); 1288// } 1289 1290// @Override 1291// public void loadMessageForViewBodyAvailable(Account account, String folder, 1292// String uid, final Message message) { 1293// // TODO: convert uid to EmailContent.Message and re-do what's below 1294// mSourceMessage = message; 1295// runOnUiThread(new Runnable() { 1296// public void run() { 1297// processSourceMessage(message); 1298// } 1299// }); 1300// } 1301 1302// @Override 1303// public void loadMessageForViewFailed(Account account, String folder, String uid, 1304// final String message) { 1305// mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); 1306// // TODO show network error 1307// } 1308// } 1309} 1310