ComposeActivity.java revision 2708306e0b6f8dde22b2571d0dbcc28a53c9f29b
1/**
2 * Copyright (c) 2011, Google Inc.
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.mail.compose;
18
19import android.app.ActionBar;
20import android.app.ActionBar.OnNavigationListener;
21import android.app.Activity;
22import android.app.ActivityManager;
23import android.app.AlertDialog;
24import android.app.Dialog;
25import android.app.Fragment;
26import android.app.FragmentTransaction;
27import android.app.LoaderManager;
28import android.content.ContentResolver;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.CursorLoader;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.Loader;
35import android.content.pm.ActivityInfo;
36import android.database.Cursor;
37import android.net.Uri;
38import android.os.Bundle;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.Parcelable;
42import android.os.ParcelFileDescriptor;
43import android.provider.BaseColumns;
44import android.text.Editable;
45import android.text.Html;
46import android.text.SpannableString;
47import android.text.Spanned;
48import android.text.TextUtils;
49import android.text.TextWatcher;
50import android.text.util.Rfc822Token;
51import android.text.util.Rfc822Tokenizer;
52import android.view.Gravity;
53import android.view.KeyEvent;
54import android.view.LayoutInflater;
55import android.view.Menu;
56import android.view.MenuInflater;
57import android.view.MenuItem;
58import android.view.View;
59import android.view.View.OnClickListener;
60import android.view.ViewGroup;
61import android.view.inputmethod.EditorInfo;
62import android.widget.ArrayAdapter;
63import android.widget.Button;
64import android.widget.EditText;
65import android.widget.TextView;
66import android.widget.Toast;
67
68import com.android.common.Rfc822Validator;
69import com.android.ex.chips.RecipientEditTextView;
70import com.android.mail.R;
71import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
72import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
73import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
74import com.android.mail.compose.QuotedTextView.RespondInlineListener;
75import com.android.mail.providers.Account;
76import com.android.mail.providers.Address;
77import com.android.mail.providers.Attachment;
78import com.android.mail.providers.MailAppProvider;
79import com.android.mail.providers.Message;
80import com.android.mail.providers.MessageModification;
81import com.android.mail.providers.ReplyFromAccount;
82import com.android.mail.providers.Settings;
83import com.android.mail.providers.UIProvider;
84import com.android.mail.providers.UIProvider.AccountCapabilities;
85import com.android.mail.providers.UIProvider.DraftType;
86import com.android.mail.ui.MailActivity;
87import com.android.mail.ui.WaitFragment;
88import com.android.mail.ui.AttachmentTile.AttachmentPreview;
89import com.android.mail.utils.AccountUtils;
90import com.android.mail.utils.AttachmentUtils;
91import com.android.mail.utils.ContentProviderTask;
92import com.android.mail.utils.LogTag;
93import com.android.mail.utils.LogUtils;
94import com.android.mail.utils.Utils;
95import com.google.common.annotations.VisibleForTesting;
96import com.google.common.collect.Lists;
97import com.google.common.collect.Sets;
98
99import java.io.FileNotFoundException;
100import java.io.IOException;
101import java.io.UnsupportedEncodingException;
102import java.net.URLDecoder;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collection;
106import java.util.HashMap;
107import java.util.HashSet;
108import java.util.List;
109import java.util.Map.Entry;
110import java.util.Set;
111import java.util.concurrent.ConcurrentHashMap;
112
113public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
114        RespondInlineListener, DialogInterface.OnClickListener, TextWatcher,
115        AttachmentAddedOrDeletedListener, OnAccountChangedListener, LoaderManager.LoaderCallbacks<Cursor>,
116        TextView.OnEditorActionListener {
117    // Identifiers for which type of composition this is
118    static final int COMPOSE = -1;
119    static final int REPLY = 0;
120    static final int REPLY_ALL = 1;
121    static final int FORWARD = 2;
122    static final int EDIT_DRAFT = 3;
123
124    // Integer extra holding one of the above compose action
125    protected static final String EXTRA_ACTION = "action";
126
127    private static final String EXTRA_SHOW_CC = "showCc";
128    private static final String EXTRA_SHOW_BCC = "showBcc";
129
130    private static final String UTF8_ENCODING_NAME = "UTF-8";
131
132    private static final String MAIL_TO = "mailto";
133
134    private static final String EXTRA_SUBJECT = "subject";
135
136    private static final String EXTRA_BODY = "body";
137
138    protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
139
140    private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
141
142    // Extra that we can get passed from other activities
143    private static final String EXTRA_TO = "to";
144    private static final String EXTRA_CC = "cc";
145    private static final String EXTRA_BCC = "bcc";
146
147    // List of all the fields
148    static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC };
149
150    private static SendOrSaveCallback sTestSendOrSaveCallback = null;
151    // Map containing information about requests to create new messages, and the id of the
152    // messages that were the result of those requests.
153    //
154    // This map is used when the activity that initiated the save a of a new message, is killed
155    // before the save has completed (and when we know the id of the newly created message).  When
156    // a save is completed, the service that is running in the background, will update the map
157    //
158    // When a new ComposeActivity instance is created, it will attempt to use the information in
159    // the previously instantiated map.  If ComposeActivity.onCreate() is called, with a bundle
160    // (restoring data from a previous instance), and the map hasn't been created, we will attempt
161    // to populate the map with data stored in shared preferences.
162    // FIXME: values in this map are never read.
163    private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
164    // Key used to store the above map
165    private static final String CACHED_MESSAGE_REQUEST_IDS_KEY = "cache-message-request-ids";
166    /**
167     * Notifies the {@code Activity} that the caller is an Email
168     * {@code Activity}, so that the back behavior may be modified accordingly.
169     *
170     * @see #onAppUpPressed
171     */
172    public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
173
174    public static final String EXTRA_ATTACHMENTS = "attachments";
175
176    //  If this is a reply/forward then this extra will hold the original message
177    private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
178    // If this is a reply/forward then this extra will hold a uri we must query
179    // to get the original message.
180    protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
181    // If this is an action to edit an existing draft message, this extra will hold the
182    // draft message
183    private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
184    private static final String END_TOKEN = ", ";
185    private static final String LOG_TAG = LogTag.getLogTag();
186    // Request numbers for activities we start
187    private static final int RESULT_PICK_ATTACHMENT = 1;
188    private static final int RESULT_CREATE_ACCOUNT = 2;
189    // TODO(mindyp) set mime-type for auto send?
190    public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
191
192    private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
193    private static final String EXTRA_REQUEST_ID = "requestId";
194    private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
195    private static final String EXTRA_FOCUS_SELECTION_END = null;
196    private static final String EXTRA_MESSAGE = "extraMessage";
197    private static final int REFERENCE_MESSAGE_LOADER = 0;
198    private static final int LOADER_ACCOUNT_CURSOR = 1;
199    private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
200    private static final String TAG_WAIT = "wait-fragment";
201    private static final String MIME_TYPE_PHOTO = "image/*";
202    private static final String MIME_TYPE_VIDEO = "video/*";
203
204    /**
205     * A single thread for running tasks in the background.
206     */
207    private Handler mSendSaveTaskHandler = null;
208    private RecipientEditTextView mTo;
209    private RecipientEditTextView mCc;
210    private RecipientEditTextView mBcc;
211    private Button mCcBccButton;
212    private CcBccView mCcBccView;
213    private AttachmentsView mAttachmentsView;
214    private Account mAccount;
215    private ReplyFromAccount mReplyFromAccount;
216    private Settings mCachedSettings;
217    private Rfc822Validator mValidator;
218    private TextView mSubject;
219
220    private ComposeModeAdapter mComposeModeAdapter;
221    private int mComposeMode = -1;
222    private boolean mForward;
223    private String mRecipient;
224    private QuotedTextView mQuotedTextView;
225    private EditText mBodyView;
226    private View mFromStatic;
227    private TextView mFromStaticText;
228    private View mFromSpinnerWrapper;
229    @VisibleForTesting
230    protected FromAddressSpinner mFromSpinner;
231    private boolean mAddingAttachment;
232    private boolean mAttachmentsChanged;
233    private boolean mTextChanged;
234    private boolean mReplyFromChanged;
235    private MenuItem mSave;
236    private MenuItem mSend;
237    private AlertDialog mRecipientErrorDialog;
238    private AlertDialog mSendConfirmDialog;
239    @VisibleForTesting
240    protected Message mRefMessage;
241    private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
242    private Message mDraft;
243    private ReplyFromAccount mDraftAccount;
244    private Object mDraftLock = new Object();
245    private View mPhotoAttachmentsButton;
246    private View mVideoAttachmentsButton;
247
248    /**
249     * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
250     */
251    private boolean mLaunchedFromEmail = false;
252    private RecipientTextWatcher mToListener;
253    private RecipientTextWatcher mCcListener;
254    private RecipientTextWatcher mBccListener;
255    private Uri mRefMessageUri;
256    private Bundle mSavedInstanceState;
257
258
259    /**
260     * Can be called from a non-UI thread.
261     */
262    public static void editDraft(Context launcher, Account account, Message message) {
263        launch(launcher, account, message, EDIT_DRAFT);
264    }
265
266    /**
267     * Can be called from a non-UI thread.
268     */
269    public static void compose(Context launcher, Account account) {
270        launch(launcher, account, null, COMPOSE);
271    }
272
273    /**
274     * Can be called from a non-UI thread.
275     */
276    public static void reply(Context launcher, Account account, Message message) {
277        launch(launcher, account, message, REPLY);
278    }
279
280    /**
281     * Can be called from a non-UI thread.
282     */
283    public static void replyAll(Context launcher, Account account, Message message) {
284        launch(launcher, account, message, REPLY_ALL);
285    }
286
287    /**
288     * Can be called from a non-UI thread.
289     */
290    public static void forward(Context launcher, Account account, Message message) {
291        launch(launcher, account, message, FORWARD);
292    }
293
294    private static void launch(Context launcher, Account account, Message message, int action) {
295        Intent intent = new Intent(launcher, ComposeActivity.class);
296        intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
297        intent.putExtra(EXTRA_ACTION, action);
298        intent.putExtra(Utils.EXTRA_ACCOUNT, account);
299        if (action == EDIT_DRAFT) {
300            intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
301        } else {
302            intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
303        }
304        launcher.startActivity(intent);
305    }
306
307    @Override
308    public void onCreate(Bundle savedInstanceState) {
309        super.onCreate(savedInstanceState);
310        setContentView(R.layout.compose);
311        mSavedInstanceState = savedInstanceState;
312        checkValidAccounts();
313    }
314
315    private void finishCreate() {
316        Bundle savedInstanceState = mSavedInstanceState;
317        findViews();
318        Intent intent = getIntent();
319        Message message;
320        ArrayList<AttachmentPreview> previews;
321        boolean showQuotedText = false;
322        int action;
323        // Check for any of the possibly supplied accounts.;
324        Account account = null;
325        if (hadSavedInstanceStateMessage(savedInstanceState)) {
326            action = savedInstanceState.getInt(EXTRA_ACTION, COMPOSE);
327            account = savedInstanceState.getParcelable(Utils.EXTRA_ACCOUNT);
328            message = (Message) savedInstanceState.getParcelable(EXTRA_MESSAGE);
329
330            previews = savedInstanceState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
331            mRefMessage = (Message) savedInstanceState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
332        } else {
333            account = obtainAccount(intent);
334            action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
335            // Initialize the message from the message in the intent
336            message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
337            previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
338            mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
339            mRefMessageUri = (Uri) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
340        }
341        mAttachmentsView.setAttachmentPreviews(previews);
342
343        setAccount(account);
344        if (mAccount == null) {
345            return;
346        }
347
348        if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
349            mLaunchedFromEmail = true;
350        } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
351            final Uri dataUri = intent.getData();
352            if (dataUri != null) {
353                final String dataScheme = intent.getData().getScheme();
354                final String accountScheme = mAccount.composeIntentUri.getScheme();
355                mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
356            }
357        }
358
359        if (mRefMessageUri != null) {
360            // We have a referenced message that we must look up.
361            getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
362            return;
363        } else if (message != null && action != EDIT_DRAFT) {
364            initFromDraftMessage(message);
365            initQuotedTextFromRefMessage(mRefMessage, action);
366            showCcBcc(savedInstanceState);
367            showQuotedText = message.appendRefMessageContent;
368        } else if (action == EDIT_DRAFT) {
369            initFromDraftMessage(message);
370            boolean showBcc = !TextUtils.isEmpty(message.getBcc());
371            boolean showCc = showBcc || !TextUtils.isEmpty(message.getCc());
372            mCcBccView.show(false, showCc, showBcc);
373            // Update the action to the draft type of the previous draft
374            switch (message.draftType) {
375                case UIProvider.DraftType.REPLY:
376                    action = REPLY;
377                    break;
378                case UIProvider.DraftType.REPLY_ALL:
379                    action = REPLY_ALL;
380                    break;
381                case UIProvider.DraftType.FORWARD:
382                    action = FORWARD;
383                    break;
384                case UIProvider.DraftType.COMPOSE:
385                default:
386                    action = COMPOSE;
387                    break;
388            }
389            initQuotedTextFromRefMessage(mRefMessage, action);
390            showQuotedText = message.appendRefMessageContent;
391        } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
392            if (mRefMessage != null) {
393                initFromRefMessage(action, mAccount.name);
394                showQuotedText = true;
395            }
396        } else {
397            initFromExtras(intent);
398        }
399        finishSetup(action, intent, savedInstanceState, showQuotedText);
400    }
401
402    private void checkValidAccounts() {
403        final Account[] allAccounts = AccountUtils.getAccounts(this);
404        if (allAccounts == null || allAccounts.length == 0) {
405            final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
406            if (noAccountIntent != null) {
407                mAccounts = null;
408                startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
409            }
410        } else {
411            // If none of the accounts are syncing, setup a watcher.
412            boolean anySyncing = false;
413            for (Account a : allAccounts) {
414                if (a.isAccountReady()) {
415                    anySyncing = true;
416                    break;
417                }
418            }
419            if (!anySyncing) {
420                // There are accounts, but none are sync'd, which is just like having no accounts.
421                mAccounts = null;
422                getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
423                return;
424            }
425            mAccounts = AccountUtils.getSyncingAccounts(this);
426            finishCreate();
427        }
428    }
429
430    private Account obtainAccount(Intent intent) {
431        Account account = null;
432        Object accountExtra = null;
433        if (intent != null && intent.getExtras() != null) {
434            accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
435            if (accountExtra instanceof Account) {
436                return (Account) accountExtra;
437            } else if (accountExtra instanceof String) {
438                // This is the Account attached to the widget compose intent.
439                account = Account.newinstance((String)accountExtra);
440                if (account != null) {
441                    return account;
442                }
443            }
444            accountExtra = intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
445        }
446        if (account == null) {
447            MailAppProvider provider = MailAppProvider.getInstance();
448            String lastAccountUri = provider.getLastSentFromAccount();
449            if (TextUtils.isEmpty(lastAccountUri)) {
450                lastAccountUri = provider.getLastViewedAccount();
451            }
452            if (!TextUtils.isEmpty(lastAccountUri)) {
453                accountExtra = Uri.parse(lastAccountUri);
454            }
455        }
456        if (mAccounts != null && mAccounts.length > 0) {
457            if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
458                // For backwards compatibility, we need to check account
459                // names.
460                for (Account a : mAccounts) {
461                    if (a.name.equals(accountExtra)) {
462                        account = a;
463                    }
464                }
465            } else if (accountExtra instanceof Uri) {
466                // The uri of the last viewed account is what is stored in
467                // the current code base.
468                for (Account a : mAccounts) {
469                    if (a.uri.equals(accountExtra)) {
470                        account = a;
471                    }
472                }
473            }
474            if (account == null) {
475                account = mAccounts[0];
476            }
477        }
478        return account;
479    }
480
481    private void finishSetup(int action, Intent intent, Bundle savedInstanceState,
482            boolean showQuotedText) {
483        setFocus(action);
484        if (action == COMPOSE) {
485            mQuotedTextView.setVisibility(View.GONE);
486        }
487        initRecipients();
488        // Don't bother with the intent if we have procured a message from the
489        // intent already.
490        if (!hadSavedInstanceStateMessage(savedInstanceState)) {
491            initAttachmentsFromIntent(intent);
492        }
493        initActionBar(action);
494        initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
495                action);
496
497        // If this is a draft message, the draft account is whatever account was
498        // used to open the draft message in Compose.
499        if (mDraft != null) {
500            mDraftAccount = mReplyFromAccount;
501        }
502
503        initChangeListeners();
504        updateHideOrShowCcBcc();
505        updateHideOrShowQuotedText(showQuotedText);
506    }
507
508    private boolean hadSavedInstanceStateMessage(Bundle savedInstanceState) {
509        return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
510    }
511
512    private void updateHideOrShowQuotedText(boolean showQuotedText) {
513        mQuotedTextView.updateCheckedState(showQuotedText);
514        mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
515    }
516
517    private void setFocus(int action) {
518        if (action == EDIT_DRAFT) {
519            int type = mDraft.draftType;
520            switch (type) {
521                case UIProvider.DraftType.COMPOSE:
522                case UIProvider.DraftType.FORWARD:
523                    action = COMPOSE;
524                    break;
525                case UIProvider.DraftType.REPLY:
526                case UIProvider.DraftType.REPLY_ALL:
527                default:
528                    action = REPLY;
529                    break;
530            }
531        }
532        switch (action) {
533            case FORWARD:
534            case COMPOSE:
535                if (TextUtils.isEmpty(mTo.getText())) {
536                    mTo.requestFocus();
537                    break;
538                }
539            case REPLY:
540            case REPLY_ALL:
541            default:
542                focusBody();
543                break;
544        }
545    }
546
547    /**
548     * Focus the body of the message.
549     */
550    public void focusBody() {
551        mBodyView.requestFocus();
552        int length = mBodyView.getText().length();
553
554        int signatureStartPos = getSignatureStartPosition(
555                mSignature, mBodyView.getText().toString());
556        if (signatureStartPos > -1) {
557            // In case the user deleted the newlines...
558            mBodyView.setSelection(signatureStartPos);
559        } else if (length >= 0) {
560            // Move cursor to the end.
561            mBodyView.setSelection(length);
562        }
563    }
564
565    @Override
566    protected void onResume() {
567        super.onResume();
568        // Update the from spinner as other accounts
569        // may now be available.
570        if (mFromSpinner != null && mAccount != null) {
571            mFromSpinner.asyncInitFromSpinner(mComposeMode, mAccount, mAccounts);
572        }
573    }
574
575    @Override
576    protected void onPause() {
577        super.onPause();
578
579        if (mSendConfirmDialog != null) {
580            mSendConfirmDialog.dismiss();
581        }
582        if (mRecipientErrorDialog != null) {
583            mRecipientErrorDialog.dismiss();
584        }
585        // When the user exits the compose view, see if this draft needs saving.
586        // Don't save unnecessary drafts if we are only changing the orientation.
587        if (!isChangingConfigurations()) {
588            saveIfNeeded();
589        }
590    }
591
592    @Override
593    protected final void onActivityResult(int request, int result, Intent data) {
594        if (request == RESULT_PICK_ATTACHMENT && result == RESULT_OK) {
595            addAttachmentAndUpdateView(data);
596            mAddingAttachment = false;
597        } else if (request == RESULT_CREATE_ACCOUNT) {
598                // We were waiting for the user to create an account
599            if (result != RESULT_OK) {
600                finish();
601            } else {
602                // Watch for accounts to show up!
603                // restart the loader to get the updated list of accounts
604                getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
605                showWaitFragment(null);
606            }
607        }
608    }
609
610    @Override
611    public final void onRestoreInstanceState(Bundle savedInstanceState) {
612        clearChangeListeners();
613        super.onRestoreInstanceState(savedInstanceState);
614        if (savedInstanceState != null) {
615            if (savedInstanceState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
616                int selectionStart = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_START);
617                int selectionEnd = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_END);
618                // There should be a focus and it should be an EditText since we
619                // only save these extras if these conditions are true.
620                EditText focusEditText = (EditText) getCurrentFocus();
621                final int length = focusEditText.getText().length();
622                if (selectionStart < length && selectionEnd < length) {
623                    focusEditText.setSelection(selectionStart, selectionEnd);
624                }
625            }
626        }
627    }
628
629    @Override
630    public final void onSaveInstanceState(Bundle state) {
631        super.onSaveInstanceState(state);
632        // We have no accounts so there is nothing to compose, and therefore, nothing to save.
633        if (mAccounts == null || mAccounts.length == 0) {
634            return;
635        }
636        // The framework is happy to save and restore the selection but only if it also saves and
637        // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
638        // this manually.
639        View focus = getCurrentFocus();
640        if (focus != null && focus instanceof EditText) {
641            EditText focusEditText = (EditText) focus;
642            state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
643            state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
644        }
645
646        final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
647        final int selectedPos = mFromSpinner.getSelectedItemPosition();
648        final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
649                && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
650                        replyFromAccounts.get(selectedPos) : null;
651        if (selectedReplyFromAccount != null) {
652            state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
653                    .toString());
654            state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
655        } else {
656            state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
657        }
658
659        if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
660            // We don't have a draft id, and we have a request id,
661            // save the request id.
662            state.putInt(EXTRA_REQUEST_ID, mRequestId);
663        }
664
665        // We want to restore the current mode after a pause
666        // or rotation.
667        int mode = getMode();
668        state.putInt(EXTRA_ACTION, mode);
669
670        final Message message = createMessage(selectedReplyFromAccount, mode);
671        if (mDraft != null) {
672            message.id = mDraft.id;
673            message.serverId = mDraft.serverId;
674            message.uri = mDraft.uri;
675        }
676        state.putParcelable(EXTRA_MESSAGE, message);
677
678        if (mRefMessage != null) {
679            state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
680        }
681        state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
682        state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
683
684        state.putParcelableArrayList(
685                EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
686    }
687
688    private int getMode() {
689        int mode = ComposeActivity.COMPOSE;
690        ActionBar actionBar = getActionBar();
691        if (actionBar != null
692                && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
693            mode = actionBar.getSelectedNavigationIndex();
694        }
695        return mode;
696    }
697
698    private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
699        Message message = new Message();
700        message.id = UIProvider.INVALID_MESSAGE_ID;
701        message.serverId = null;
702        message.uri = null;
703        message.conversationUri = null;
704        message.subject = mSubject.getText().toString();
705        message.snippet = null;
706        message.setTo(formatSenders(mTo.getText().toString()));
707        message.setCc(formatSenders(mCc.getText().toString()));
708        message.setBcc(formatSenders(mBcc.getText().toString()));
709        message.setReplyTo(null);
710        message.dateReceivedMs = 0;
711        String htmlBody = Html.toHtml(new SpannableString(mBodyView.getText().toString()));
712        StringBuilder fullBody = new StringBuilder(htmlBody);
713        message.bodyHtml = fullBody.toString();
714        message.bodyText = mBodyView.getText().toString();
715        message.embedsExternalResources = false;
716        message.refMessageId = mRefMessage != null ? mRefMessage.uri.toString() : null;
717        message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
718        ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
719        message.hasAttachments = attachments != null && attachments.size() > 0;
720        message.attachmentListUri = null;
721        message.messageFlags = 0;
722        message.saveUri = null;
723        message.sendUri = null;
724        message.alwaysShowImages = false;
725        message.attachmentsJson = Attachment.toJSONArray(attachments);
726        CharSequence quotedText = mQuotedTextView.getQuotedText();
727        message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
728                .getQuotedTextOffset(quotedText.toString()) : -1;
729        message.accountUri = null;
730        message.setFrom(selectedReplyFromAccount != null ? selectedReplyFromAccount.address
731                : mAccount != null ? mAccount.name : null);
732        message.draftType = getDraftType(mode);
733        message.setTo(formatSenders(mTo.getText().toString()));
734        message.setCc(formatSenders(mCc.getText().toString()));
735        message.setBcc(formatSenders(mBcc.getText().toString()));
736        return message;
737    }
738
739    private String formatSenders(String string) {
740        if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
741            return string.substring(0, string.length() - 1);
742        }
743        return string;
744    }
745
746    @VisibleForTesting
747    void setAccount(Account account) {
748        if (account == null) {
749            return;
750        }
751        if (!account.equals(mAccount)) {
752            mAccount = account;
753            mCachedSettings = mAccount.settings;
754            appendSignature();
755        }
756        if (mAccount != null) {
757            MailActivity.setForegroundNdef(MailActivity.getMailtoNdef(mAccount.name));
758        }
759    }
760
761    private void initFromSpinner(Bundle bundle, int action) {
762        String accountString = null;
763        if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
764            action = COMPOSE;
765        }
766        mFromSpinner.asyncInitFromSpinner(action, mAccount, mAccounts);
767        if (bundle != null) {
768            if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
769                mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
770                        bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
771            } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
772                accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
773                mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
774            }
775        }
776        if (mReplyFromAccount == null) {
777            if (mDraft != null) {
778                mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
779            } else if (mRefMessage != null) {
780                mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
781            }
782        }
783        if (mReplyFromAccount == null) {
784            mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
785        }
786
787        mFromSpinner.setCurrentAccount(mReplyFromAccount);
788
789        if (mFromSpinner.getCount() > 1) {
790            // If there is only 1 account, just show that account.
791            // Otherwise, give the user the ability to choose which account to
792            // send mail from / save drafts to.
793            mFromStatic.setVisibility(View.GONE);
794            mFromStaticText.setText(mAccount.name);
795            mFromSpinnerWrapper.setVisibility(View.VISIBLE);
796        } else {
797            mFromStatic.setVisibility(View.VISIBLE);
798            mFromStaticText.setText(mAccount.name);
799            mFromSpinnerWrapper.setVisibility(View.GONE);
800        }
801    }
802
803    private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
804        if (refMessage.accountUri != null) {
805            // This must be from combined inbox.
806            List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
807            for (ReplyFromAccount from : replyFromAccounts) {
808                if (from.account.uri.equals(refMessage.accountUri)) {
809                    return from;
810                }
811            }
812            return null;
813        } else {
814            return getReplyFromAccount(account, refMessage);
815        }
816    }
817
818    /**
819     * Given an account and which email address the message was sent to,
820     * return who the message should be sent from.
821     * @param account Account in which the message arrived.
822     * @param sentTo Email address to which the message was sent.
823     * @return the address from which to reply.
824     */
825    public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
826        // First see if we are supposed to use the default address or
827        // the address it was sentTo.
828        if (mCachedSettings.forceReplyFromDefault) {
829            return getDefaultReplyFromAccount(account);
830        } else {
831            // If we aren't explicitly told which account to look for, look at
832            // all the message recipients and find one that matches
833            // a custom from or account.
834            List<String> allRecipients = new ArrayList<String>();
835            allRecipients.addAll(Arrays.asList(refMessage.getToAddresses()));
836            allRecipients.addAll(Arrays.asList(refMessage.getCcAddresses()));
837            return getMatchingRecipient(account, allRecipients);
838        }
839    }
840
841    /**
842     * Compare all the recipients of an email to the current account and all
843     * custom addresses associated with that account. Return the match if there
844     * is one, or the default account if there isn't.
845     */
846    protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
847        // Tokenize the list and place in a hashmap.
848        ReplyFromAccount matchingReplyFrom = null;
849        Rfc822Token[] tokens;
850        HashSet<String> recipientsMap = new HashSet<String>();
851        for (String address : sentTo) {
852            tokens = Rfc822Tokenizer.tokenize(address);
853            for (int i = 0; i < tokens.length; i++) {
854                recipientsMap.add(tokens[i].getAddress());
855            }
856        }
857
858        int matchingAddressCount = 0;
859        List<ReplyFromAccount> customFroms;
860        customFroms = account.getReplyFroms();
861        if (customFroms != null) {
862            for (ReplyFromAccount entry : customFroms) {
863                if (recipientsMap.contains(entry.address)) {
864                    matchingReplyFrom = entry;
865                    matchingAddressCount++;
866                }
867            }
868        }
869        if (matchingAddressCount > 1) {
870            matchingReplyFrom = getDefaultReplyFromAccount(account);
871        }
872        return matchingReplyFrom;
873    }
874
875    private ReplyFromAccount getDefaultReplyFromAccount(Account account) {
876        for (ReplyFromAccount from : account.getReplyFroms()) {
877            if (from.isDefault) {
878                return from;
879            }
880        }
881        return new ReplyFromAccount(account, account.uri, account.name, account.name, account.name,
882                true, false);
883    }
884
885    private ReplyFromAccount getReplyFromAccountFromDraft(Account account, Message msg) {
886        String sender = msg.getFrom();
887        ReplyFromAccount replyFromAccount = null;
888        List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
889        if (TextUtils.equals(account.name, sender)) {
890            replyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
891                    mAccount.name, mAccount.name, true, false);
892        } else {
893            for (ReplyFromAccount fromAccount : replyFromAccounts) {
894                if (TextUtils.equals(fromAccount.name, sender)) {
895                    replyFromAccount = fromAccount;
896                    break;
897                }
898            }
899        }
900        return replyFromAccount;
901    }
902
903    private void findViews() {
904        findViewById(R.id.compose).setVisibility(View.VISIBLE);
905        mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
906        if (mCcBccButton != null) {
907            mCcBccButton.setOnClickListener(this);
908        }
909        mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
910        mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
911        mPhotoAttachmentsButton = findViewById(R.id.add_photo_attachment);
912        if (mPhotoAttachmentsButton != null) {
913            mPhotoAttachmentsButton.setOnClickListener(this);
914        }
915        mVideoAttachmentsButton = findViewById(R.id.add_video_attachment);
916        if (mVideoAttachmentsButton != null) {
917            mVideoAttachmentsButton.setOnClickListener(this);
918        }
919        mTo = (RecipientEditTextView) findViewById(R.id.to);
920        mCc = (RecipientEditTextView) findViewById(R.id.cc);
921        mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
922        // TODO: add special chips text change watchers before adding
923        // this as a text changed watcher to the to, cc, bcc fields.
924        mSubject = (TextView) findViewById(R.id.subject);
925        mSubject.setOnEditorActionListener(this);
926        mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
927        mQuotedTextView.setRespondInlineListener(this);
928        mBodyView = (EditText) findViewById(R.id.body);
929        mFromStatic = findViewById(R.id.static_from_content);
930        mFromStaticText = (TextView) findViewById(R.id.from_account_name);
931        mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
932        mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
933    }
934
935    @Override
936    public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
937        if (action == EditorInfo.IME_ACTION_DONE) {
938            focusBody();
939            return true;
940        }
941        return false;
942    }
943
944    protected TextView getBody() {
945        return mBodyView;
946    }
947
948    @VisibleForTesting
949    public Account getFromAccount() {
950        return mReplyFromAccount != null && mReplyFromAccount.account != null ?
951                mReplyFromAccount.account : mAccount;
952    }
953
954    private void clearChangeListeners() {
955        mSubject.removeTextChangedListener(this);
956        mBodyView.removeTextChangedListener(this);
957        mTo.removeTextChangedListener(mToListener);
958        mCc.removeTextChangedListener(mCcListener);
959        mBcc.removeTextChangedListener(mBccListener);
960        mFromSpinner.setOnAccountChangedListener(null);
961        mAttachmentsView.setAttachmentChangesListener(null);
962    }
963
964    // Now that the message has been initialized from any existing draft or
965    // ref message data, set up listeners for any changes that occur to the
966    // message.
967    private void initChangeListeners() {
968        mSubject.addTextChangedListener(this);
969        mBodyView.addTextChangedListener(this);
970        if (mToListener == null) {
971            mToListener = new RecipientTextWatcher(mTo, this);
972        }
973        mTo.addTextChangedListener(mToListener);
974        if (mCcListener == null) {
975            mCcListener = new RecipientTextWatcher(mCc, this);
976        }
977        mCc.addTextChangedListener(mCcListener);
978        if (mBccListener == null) {
979            mBccListener = new RecipientTextWatcher(mBcc, this);
980        }
981        mBcc.addTextChangedListener(mBccListener);
982        mFromSpinner.setOnAccountChangedListener(this);
983        mAttachmentsView.setAttachmentChangesListener(this);
984    }
985
986    private void initActionBar(int action) {
987        mComposeMode = action;
988        ActionBar actionBar = getActionBar();
989        if (actionBar == null) {
990            return;
991        }
992        if (action == ComposeActivity.COMPOSE) {
993            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
994            actionBar.setTitle(R.string.compose);
995        } else {
996            actionBar.setTitle(null);
997            if (mComposeModeAdapter == null) {
998                mComposeModeAdapter = new ComposeModeAdapter(this);
999            }
1000            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1001            actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
1002            switch (action) {
1003                case ComposeActivity.REPLY:
1004                    actionBar.setSelectedNavigationItem(0);
1005                    break;
1006                case ComposeActivity.REPLY_ALL:
1007                    actionBar.setSelectedNavigationItem(1);
1008                    break;
1009                case ComposeActivity.FORWARD:
1010                    actionBar.setSelectedNavigationItem(2);
1011                    break;
1012            }
1013        }
1014        actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
1015                ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
1016        actionBar.setHomeButtonEnabled(true);
1017    }
1018
1019    private void initFromRefMessage(int action, String recipientAddress) {
1020        setFieldsFromRefMessage(action, recipientAddress);
1021        if (mRefMessage != null) {
1022            // CC field only gets populated when doing REPLY_ALL.
1023            // BCC never gets auto-populated, unless the user is editing
1024            // a draft with one.
1025            if (!TextUtils.isEmpty(mCc.getText()) && action == REPLY_ALL) {
1026                mCcBccView.show(false, true, false);
1027            }
1028        }
1029        updateHideOrShowCcBcc();
1030    }
1031
1032    private void setFieldsFromRefMessage(int action, String recipientAddress) {
1033        setSubject(mRefMessage, action);
1034        // Setup recipients
1035        if (action == FORWARD) {
1036            mForward = true;
1037        }
1038        initRecipientsFromRefMessage(recipientAddress, mRefMessage, action);
1039        initQuotedTextFromRefMessage(mRefMessage, action);
1040        if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1041            initAttachments(mRefMessage);
1042        }
1043    }
1044
1045    private void initFromDraftMessage(Message message) {
1046        LogUtils.d(LOG_TAG, "Intializing draft from previous draft message: %s", message);
1047
1048        mDraft = message;
1049        mDraftId = message.id;
1050        mSubject.setText(message.subject);
1051        mForward = message.draftType == UIProvider.DraftType.FORWARD;
1052        final List<String> toAddresses = Arrays.asList(message.getToAddresses());
1053        addToAddresses(toAddresses);
1054        addCcAddresses(Arrays.asList(message.getCcAddresses()), toAddresses);
1055        addBccAddresses(Arrays.asList(message.getBccAddresses()));
1056        if (message.hasAttachments) {
1057            List<Attachment> attachments = message.getAttachments();
1058            for (Attachment a : attachments) {
1059                addAttachmentAndUpdateView(a);
1060            }
1061        }
1062        int quotedTextIndex = message.appendRefMessageContent ?
1063                message.quotedTextOffset : -1;
1064        // Set the body
1065        CharSequence quotedText = null;
1066        if (!TextUtils.isEmpty(message.bodyHtml)) {
1067            CharSequence htmlText = "";
1068            if (quotedTextIndex > -1) {
1069                // Find the offset in the htmltext of the actual quoted text and strip it out.
1070                quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1071                if (quotedTextIndex > -1) {
1072                    htmlText = Utils.convertHtmlToPlainText(message.bodyHtml.substring(0,
1073                            quotedTextIndex));
1074                    quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1075                            message.bodyHtml.length());
1076                }
1077            } else {
1078                htmlText = Utils.convertHtmlToPlainText(message.bodyHtml);
1079            }
1080            mBodyView.setText(htmlText);
1081        } else {
1082            final String body = message.bodyText;
1083            final CharSequence bodyText = !TextUtils.isEmpty(body) ?
1084                    (quotedTextIndex > -1 ?
1085                            message.bodyText.substring(0, quotedTextIndex) : message.bodyText)
1086                            : "";
1087            if (quotedTextIndex > -1) {
1088                quotedText = !TextUtils.isEmpty(body) ? message.bodyText.substring(quotedTextIndex)
1089                        : null;
1090            }
1091            mBodyView.setText(bodyText);
1092        }
1093        if (quotedTextIndex > -1 && quotedText != null) {
1094            mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
1095        }
1096    }
1097
1098    /**
1099     * Fill all the widgets with the content found in the Intent Extra, if any.
1100     * Also apply the same style to all widgets. Note: if initFromExtras is
1101     * called as a result of switching between reply, reply all, and forward per
1102     * the latest revision of Gmail, and the user has already made changes to
1103     * attachments on a previous incarnation of the message (as a reply, reply
1104     * all, or forward), the original attachments from the message will not be
1105     * re-instantiated. The user's changes will be respected. This follows the
1106     * web gmail interaction.
1107     */
1108    public void initFromExtras(Intent intent) {
1109        // If we were invoked with a SENDTO intent, the value
1110        // should take precedence
1111        final Uri dataUri = intent.getData();
1112        if (dataUri != null) {
1113            if (MAIL_TO.equals(dataUri.getScheme())) {
1114                initFromMailTo(dataUri.toString());
1115            } else {
1116                if (!mAccount.composeIntentUri.equals(dataUri)) {
1117                    String toText = dataUri.getSchemeSpecificPart();
1118                    if (toText != null) {
1119                        mTo.setText("");
1120                        addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
1121                    }
1122                }
1123            }
1124        }
1125
1126        String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1127        if (extraStrings != null) {
1128            addToAddresses(Arrays.asList(extraStrings));
1129        }
1130        extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1131        if (extraStrings != null) {
1132            addCcAddresses(Arrays.asList(extraStrings), null);
1133        }
1134        extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1135        if (extraStrings != null) {
1136            addBccAddresses(Arrays.asList(extraStrings));
1137        }
1138
1139        String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1140        if (extraString != null) {
1141            mSubject.setText(extraString);
1142        }
1143
1144        for (String extra : ALL_EXTRAS) {
1145            if (intent.hasExtra(extra)) {
1146                String value = intent.getStringExtra(extra);
1147                if (EXTRA_TO.equals(extra)) {
1148                    addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
1149                } else if (EXTRA_CC.equals(extra)) {
1150                    addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
1151                } else if (EXTRA_BCC.equals(extra)) {
1152                    addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
1153                } else if (EXTRA_SUBJECT.equals(extra)) {
1154                    mSubject.setText(value);
1155                } else if (EXTRA_BODY.equals(extra)) {
1156                    setBody(value, true /* with signature */);
1157                }
1158            }
1159        }
1160
1161        Bundle extras = intent.getExtras();
1162        if (extras != null) {
1163            CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1164            if (text != null) {
1165                setBody(text, true /* with signature */);
1166            }
1167        }
1168    }
1169
1170    @VisibleForTesting
1171    protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
1172        // TODO: handle the case where there are spaces in the display name as
1173        // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1174        // as they could be encoded ambiguously.
1175        // Since URLDecode.decode changes + into ' ', and + is a valid
1176        // email character, we need to find/ replace these ourselves before
1177        // decoding.
1178        String replacePlus = s.replace("+", "%2B");
1179        try {
1180            return URLDecoder.decode(replacePlus, UTF8_ENCODING_NAME);
1181        } catch (IllegalArgumentException e) {
1182            if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1183                LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1184            } else {
1185                LogUtils.e(LOG_TAG, e, "Exception  while decoding mailto address");
1186            }
1187            return null;
1188        }
1189    }
1190
1191    /**
1192     * Initialize the compose view from a String representing a mailTo uri.
1193     * @param mailToString The uri as a string.
1194     */
1195    public void initFromMailTo(String mailToString) {
1196        // We need to disguise this string as a URI in order to parse it
1197        // TODO:  Remove this hack when http://b/issue?id=1445295 gets fixed
1198        Uri uri = Uri.parse("foo://" + mailToString);
1199        int index = mailToString.indexOf("?");
1200        int length = "mailto".length() + 1;
1201        String to;
1202        try {
1203            // Extract the recipient after mailto:
1204            if (index == -1) {
1205                to = decodeEmailInUri(mailToString.substring(length));
1206            } else {
1207                to = decodeEmailInUri(mailToString.substring(length, index));
1208            }
1209            if (!TextUtils.isEmpty(to)) {
1210                addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1211            }
1212        } catch (UnsupportedEncodingException e) {
1213            if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1214                LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1215            } else {
1216                LogUtils.e(LOG_TAG, e, "Exception  while decoding mailto address");
1217            }
1218        }
1219
1220        List<String> cc = uri.getQueryParameters("cc");
1221        addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1222
1223        List<String> otherTo = uri.getQueryParameters("to");
1224        addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1225
1226        List<String> bcc = uri.getQueryParameters("bcc");
1227        addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1228
1229        List<String> subject = uri.getQueryParameters("subject");
1230        if (subject.size() > 0) {
1231            try {
1232                mSubject.setText(URLDecoder.decode(subject.get(0), UTF8_ENCODING_NAME));
1233            } catch (UnsupportedEncodingException e) {
1234                LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
1235                        e.getMessage(), subject);
1236            }
1237        }
1238
1239        List<String> body = uri.getQueryParameters("body");
1240        if (body.size() > 0) {
1241            try {
1242                setBody(URLDecoder.decode(body.get(0), UTF8_ENCODING_NAME),
1243                        true /* with signature */);
1244            } catch (UnsupportedEncodingException e) {
1245                LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
1246            }
1247        }
1248    }
1249
1250    @VisibleForTesting
1251    protected void initAttachments(Message refMessage) {
1252        addAttachments(refMessage.getAttachments());
1253    }
1254
1255    public long addAttachments(List<Attachment> attachments) {
1256        long size = 0;
1257        AttachmentFailureException error = null;
1258        for (Attachment a : attachments) {
1259            try {
1260                size += mAttachmentsView.addAttachment(mAccount, a);
1261            } catch (AttachmentFailureException e) {
1262                error = e;
1263            }
1264        }
1265        if (error != null) {
1266            LogUtils.e(LOG_TAG, error, "Error adding attachment");
1267            if (attachments.size() > 1) {
1268                showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1269            } else {
1270                showAttachmentTooBigToast(error.getErrorRes());
1271            }
1272        }
1273        return size;
1274    }
1275
1276    /**
1277     * When an attachment is too large to be added to a message, show a toast.
1278     * This method also updates the position of the toast so that it is shown
1279     * clearly above they keyboard if it happens to be open.
1280     */
1281    private void showAttachmentTooBigToast(int errorRes) {
1282        String maxSize = AttachmentUtils.convertToHumanReadableSize(
1283                getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1284        showErrorToast(getString(errorRes, maxSize));
1285    }
1286
1287    private void showErrorToast(String message) {
1288        Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1289        t.setText(message);
1290        t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1291                getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1292        t.show();
1293    }
1294
1295    private void initAttachmentsFromIntent(Intent intent) {
1296        Bundle extras = intent.getExtras();
1297        if (extras == null) {
1298            extras = Bundle.EMPTY;
1299        }
1300        final String action = intent.getAction();
1301        if (!mAttachmentsChanged) {
1302            long totalSize = 0;
1303            if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1304                String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1305                for (String uriString : uris) {
1306                    final Uri uri = Uri.parse(uriString);
1307                    long size = 0;
1308                    try {
1309                        size =  mAttachmentsView.addAttachment(mAccount, uri);
1310                    } catch (AttachmentFailureException e) {
1311                        LogUtils.e(LOG_TAG, e, "Error adding attachment");
1312                        showAttachmentTooBigToast(e.getErrorRes());
1313                    }
1314                    totalSize += size;
1315                }
1316            }
1317            if (extras.containsKey(Intent.EXTRA_STREAM)) {
1318                if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1319                    ArrayList<Parcelable> uris = extras
1320                            .getParcelableArrayList(Intent.EXTRA_STREAM);
1321                    ArrayList<Attachment> attachments = new ArrayList<Attachment>();
1322                    for (Parcelable uri : uris) {
1323                        try {
1324                            attachments.add(mAttachmentsView.generateLocalAttachment((Uri) uri));
1325                        } catch (AttachmentFailureException e) {
1326                            LogUtils.e(LOG_TAG, e, "Error adding attachment");
1327                            String maxSize = AttachmentUtils.convertToHumanReadableSize(
1328                                    getApplicationContext(),
1329                                    mAccount.settings.getMaxAttachmentSize());
1330                            showErrorToast(getString
1331                                    (R.string.generic_attachment_problem, maxSize));
1332                        }
1333                    }
1334                    totalSize += addAttachments(attachments);
1335                } else {
1336                    final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
1337                    long size = 0;
1338                    try {
1339                        size = mAttachmentsView.addAttachment(mAccount, uri);
1340                    } catch (AttachmentFailureException e) {
1341                        LogUtils.e(LOG_TAG, e, "Error adding attachment");
1342                        showAttachmentTooBigToast(e.getErrorRes());
1343                    }
1344                    totalSize += size;
1345                }
1346            }
1347
1348            if (totalSize > 0) {
1349                mAttachmentsChanged = true;
1350                updateSaveUi();
1351            }
1352        }
1353    }
1354
1355
1356    private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1357        if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
1358            mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1359        }
1360    }
1361
1362    private void updateHideOrShowCcBcc() {
1363        // Its possible there is a menu item OR a button.
1364        boolean ccVisible = mCcBccView.isCcVisible();
1365        boolean bccVisible = mCcBccView.isBccVisible();
1366        if (mCcBccButton != null) {
1367            if (!ccVisible || !bccVisible) {
1368                mCcBccButton.setVisibility(View.VISIBLE);
1369                mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
1370                        : R.string.add_bcc_label));
1371            } else {
1372                mCcBccButton.setVisibility(View.INVISIBLE);
1373            }
1374        }
1375    }
1376
1377    private void showCcBcc(Bundle state) {
1378        if (state != null && state.containsKey(EXTRA_SHOW_CC)) {
1379            boolean showCc = state.getBoolean(EXTRA_SHOW_CC);
1380            boolean showBcc = state.getBoolean(EXTRA_SHOW_BCC);
1381            if (showCc || showBcc) {
1382                mCcBccView.show(false, showCc, showBcc);
1383            }
1384        }
1385    }
1386
1387    /**
1388     * Add attachment and update the compose area appropriately.
1389     * @param data
1390     */
1391    public void addAttachmentAndUpdateView(Intent data) {
1392        addAttachmentAndUpdateView(data != null ? data.getData() : (Uri) null);
1393    }
1394
1395    public void addAttachmentAndUpdateView(Uri contentUri) {
1396        if (contentUri == null) {
1397            return;
1398        }
1399        try {
1400            addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1401        } catch (AttachmentFailureException e) {
1402            LogUtils.e(LOG_TAG, e, "Error adding attachment");
1403            showErrorToast(getResources().getString(
1404                    e.getErrorRes(),
1405                    AttachmentUtils.convertToHumanReadableSize(
1406                            getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
1407        }
1408    }
1409
1410    public void addAttachmentAndUpdateView(Attachment attachment) {
1411        try {
1412            long size = mAttachmentsView.addAttachment(mAccount, attachment);
1413            if (size > 0) {
1414                mAttachmentsChanged = true;
1415                updateSaveUi();
1416            }
1417        } catch (AttachmentFailureException e) {
1418            LogUtils.e(LOG_TAG, e, "Error adding attachment");
1419            showAttachmentTooBigToast(e.getErrorRes());
1420        }
1421    }
1422
1423    void initRecipientsFromRefMessage(String recipientAddress, Message refMessage,
1424            int action) {
1425        // Don't populate the address if this is a forward.
1426        if (action == ComposeActivity.FORWARD) {
1427            return;
1428        }
1429        initReplyRecipients(mAccount.name, refMessage, action);
1430    }
1431
1432    @VisibleForTesting
1433    void initReplyRecipients(String account, Message refMessage, int action) {
1434        // This is the email address of the current user, i.e. the one composing
1435        // the reply.
1436        final String accountEmail = Address.getEmailAddress(account).getAddress();
1437        String[] sentToAddresses = refMessage.getToAddresses();
1438        String replytoAddress = refMessage.getReplyTo();
1439        final Collection<String> toAddresses;
1440
1441        // If this is a reply, the Cc list is empty. If this is a reply-all, the
1442        // Cc list is the union of the To and Cc recipients of the original
1443        // message, excluding the current user's email address and any addresses
1444        // already on the To list.
1445        if (action == ComposeActivity.REPLY) {
1446            toAddresses = initToRecipients(account, accountEmail, refMessage.getFrom(),
1447                    replytoAddress, sentToAddresses);
1448            addToAddresses(toAddresses);
1449        } else if (action == ComposeActivity.REPLY_ALL) {
1450            final Set<String> ccAddresses = Sets.newHashSet();
1451            toAddresses = initToRecipients(account, accountEmail, refMessage.getFrom(),
1452                    replytoAddress, sentToAddresses);
1453            addToAddresses(toAddresses);
1454            addRecipients(accountEmail, ccAddresses, sentToAddresses);
1455            addRecipients(accountEmail, ccAddresses, refMessage.getCcAddresses());
1456            addCcAddresses(ccAddresses, toAddresses);
1457        }
1458    }
1459
1460    private String getAddress(String toParse) {
1461        if (!TextUtils.isEmpty(toParse)) {
1462            Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(toParse);
1463            if (tokens.length > 0) {
1464                return tokens[0].getAddress();
1465            }
1466        }
1467        return "";
1468    }
1469
1470    private void addToAddresses(Collection<String> addresses) {
1471        addAddressesToList(addresses, mTo);
1472    }
1473
1474    private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
1475        addCcAddressesToList(tokenizeAddressList(addresses),
1476                toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
1477    }
1478
1479    private void addBccAddresses(Collection<String> addresses) {
1480        addAddressesToList(addresses, mBcc);
1481    }
1482
1483    @VisibleForTesting
1484    protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1485            List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1486        String address;
1487
1488        if (compareToList == null) {
1489            for (Rfc822Token[] tokens : addresses) {
1490                for (int i = 0; i < tokens.length; i++) {
1491                    address = tokens[i].toString();
1492                    list.append(address + END_TOKEN);
1493                }
1494            }
1495        } else {
1496            HashSet<String> compareTo = convertToHashSet(compareToList);
1497            for (Rfc822Token[] tokens : addresses) {
1498                for (int i = 0; i < tokens.length; i++) {
1499                    address = tokens[i].toString();
1500                    // Check if this is a duplicate:
1501                    if (!compareTo.contains(tokens[i].getAddress())) {
1502                        // Get the address here
1503                        list.append(address + END_TOKEN);
1504                    }
1505                }
1506            }
1507        }
1508    }
1509
1510    private HashSet<String> convertToHashSet(List<Rfc822Token[]> list) {
1511        HashSet<String> hash = new HashSet<String>();
1512        for (Rfc822Token[] tokens : list) {
1513            for (int i = 0; i < tokens.length; i++) {
1514                hash.add(tokens[i].getAddress());
1515            }
1516        }
1517        return hash;
1518    }
1519
1520    protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1521        @VisibleForTesting
1522        List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1523
1524        for (String address: addresses) {
1525            tokenized.add(Rfc822Tokenizer.tokenize(address));
1526        }
1527        return tokenized;
1528    }
1529
1530    @VisibleForTesting
1531    void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1532        for (String address : addresses) {
1533            addAddressToList(address, list);
1534        }
1535    }
1536
1537    private void addAddressToList(String address, RecipientEditTextView list) {
1538        if (address == null || list == null)
1539            return;
1540
1541        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
1542
1543        for (int i = 0; i < tokens.length; i++) {
1544            list.append(tokens[i] + END_TOKEN);
1545        }
1546    }
1547
1548    @VisibleForTesting
1549    protected Collection<String> initToRecipients(String account, String accountEmail,
1550            String fullSenderAddress, String replyToAddress,
1551            String[] inToAddresses) {
1552        // The To recipient is the reply-to address specified in the original
1553        // message, unless it is:
1554        // the current user OR a custom from of the current user, in which case
1555        // it's the To recipient list of the original message.
1556        // OR missing, in which case use the sender of the original message
1557        Set<String> toAddresses = Sets.newHashSet();
1558        if (!TextUtils.isEmpty(replyToAddress)
1559                && !recipientMatchesThisAccount(account, replyToAddress)) {
1560            toAddresses.add(replyToAddress);
1561        } else {
1562            if (!recipientMatchesThisAccount(account, fullSenderAddress)) {
1563                toAddresses.add(fullSenderAddress);
1564            } else {
1565                // This happens if the user replies to a message they originally
1566                // wrote. In this case, "reply" really means "re-send," so we
1567                // target the original recipients. This works as expected even
1568                // if the user sent the original message to themselves.
1569                for (String address : inToAddresses) {
1570                    if (!recipientMatchesThisAccount(account, address)) {
1571                        toAddresses.add(address);
1572                    }
1573                }
1574            }
1575        }
1576        return toAddresses;
1577    }
1578
1579    private void addRecipients(String accountAddress, Set<String> recipients, String[] addresses) {
1580        for (String email : addresses) {
1581            // Do not add this account, or any of its custom from addresses, to
1582            // the list of recipients.
1583            final String recipientAddress = Address.getEmailAddress(email).getAddress();
1584            if (!recipientMatchesThisAccount(accountAddress, recipientAddress)) {
1585                recipients.add(email.replace("\"\"", ""));
1586            }
1587        }
1588    }
1589
1590    /**
1591     * A recipient matches this account if it has the same address as the
1592     * currently selected account OR one of the custom from addresses associated
1593     * with the currently selected account.
1594     * @param accountAddress currently selected account
1595     * @param recipientAddress address we are comparing with the currently selected account
1596     * @return
1597     */
1598    protected boolean recipientMatchesThisAccount(String accountAddress, String recipientAddress) {
1599        return accountAddress.equalsIgnoreCase(recipientAddress)
1600                || ReplyFromAccount.isCustomFrom(recipientAddress,
1601                        mAccount.getReplyFroms());
1602    }
1603
1604    private void setSubject(Message refMessage, int action) {
1605        String subject = refMessage.subject;
1606        String prefix;
1607        String correctedSubject = null;
1608        if (action == ComposeActivity.COMPOSE) {
1609            prefix = "";
1610        } else if (action == ComposeActivity.FORWARD) {
1611            prefix = getString(R.string.forward_subject_label);
1612        } else {
1613            prefix = getString(R.string.reply_subject_label);
1614        }
1615
1616        // Don't duplicate the prefix
1617        if (!TextUtils.isEmpty(subject)
1618                && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
1619            correctedSubject = subject;
1620        } else {
1621            correctedSubject = String
1622                    .format(getString(R.string.formatted_subject), prefix, subject);
1623        }
1624        mSubject.setText(correctedSubject);
1625    }
1626
1627    private void initRecipients() {
1628        setupRecipients(mTo);
1629        setupRecipients(mCc);
1630        setupRecipients(mBcc);
1631    }
1632
1633    private void setupRecipients(RecipientEditTextView view) {
1634        view.setAdapter(new RecipientAdapter(this, mAccount));
1635        view.setTokenizer(new Rfc822Tokenizer());
1636        if (mValidator == null) {
1637            final String accountName = mAccount.name;
1638            int offset = accountName.indexOf("@") + 1;
1639            String account = accountName;
1640            if (offset > -1) {
1641                account = account.substring(accountName.indexOf("@") + 1);
1642            }
1643            mValidator = new Rfc822Validator(account);
1644        }
1645        view.setValidator(mValidator);
1646    }
1647
1648    @Override
1649    public void onClick(View v) {
1650        int id = v.getId();
1651        switch (id) {
1652            case R.id.add_cc_bcc:
1653                // Verify that cc/ bcc aren't showing.
1654                // Animate in cc/bcc.
1655                showCcBccViews();
1656                break;
1657            case R.id.add_photo_attachment:
1658                doAttach(MIME_TYPE_PHOTO);
1659                break;
1660            case R.id.add_video_attachment:
1661                doAttach(MIME_TYPE_VIDEO);
1662                break;
1663        }
1664    }
1665
1666    @Override
1667    public boolean onCreateOptionsMenu(Menu menu) {
1668        super.onCreateOptionsMenu(menu);
1669        // Don't render any menu items when there are no accounts.
1670        if (mAccounts == null || mAccounts.length == 0) {
1671            return true;
1672        }
1673        MenuInflater inflater = getMenuInflater();
1674        inflater.inflate(R.menu.compose_menu, menu);
1675        mSave = menu.findItem(R.id.save);
1676        mSend = menu.findItem(R.id.send);
1677        MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
1678        MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
1679        if (helpItem != null) {
1680            helpItem.setVisible(mAccount != null
1681                    && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
1682        }
1683        if (sendFeedbackItem != null) {
1684            sendFeedbackItem.setVisible(mAccount != null
1685                    && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
1686        }
1687        return true;
1688    }
1689
1690    @Override
1691    public boolean onPrepareOptionsMenu(Menu menu) {
1692        MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
1693        if (ccBcc != null && mCc != null) {
1694            // Its possible there is a menu item OR a button.
1695            boolean ccFieldVisible = mCc.isShown();
1696            boolean bccFieldVisible = mBcc.isShown();
1697            if (!ccFieldVisible || !bccFieldVisible) {
1698                ccBcc.setVisible(true);
1699                ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
1700                        : R.string.add_bcc_label));
1701            } else {
1702                ccBcc.setVisible(false);
1703            }
1704        }
1705        if (mSave != null) {
1706            mSave.setEnabled(shouldSave());
1707        }
1708        return true;
1709    }
1710
1711    @Override
1712    public boolean onOptionsItemSelected(MenuItem item) {
1713        int id = item.getItemId();
1714        boolean handled = true;
1715        switch (id) {
1716            case R.id.add_photo_attachment:
1717                doAttach(MIME_TYPE_PHOTO);
1718                break;
1719            case R.id.add_video_attachment:
1720                doAttach(MIME_TYPE_VIDEO);
1721                break;
1722            case R.id.add_cc_bcc:
1723                showCcBccViews();
1724                break;
1725            case R.id.save:
1726                doSave(true);
1727                break;
1728            case R.id.send:
1729                doSend();
1730                break;
1731            case R.id.discard:
1732                doDiscard();
1733                break;
1734            case R.id.settings:
1735                Utils.showSettings(this, mAccount);
1736                break;
1737            case android.R.id.home:
1738                onAppUpPressed();
1739                break;
1740            case R.id.help_info_menu_item:
1741                Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
1742                break;
1743            case R.id.feedback_menu_item:
1744                Utils.sendFeedback(this, mAccount, false);
1745                break;
1746            default:
1747                handled = false;
1748                break;
1749        }
1750        return !handled ? super.onOptionsItemSelected(item) : handled;
1751    }
1752
1753    @Override
1754    public void onBackPressed() {
1755        // If we are showing the wait fragment, just exit.
1756        if (getWaitFragment() != null) {
1757            finish();
1758        } else {
1759            super.onBackPressed();
1760        }
1761    }
1762
1763    /**
1764     * Carries out the "up" action in the action bar.
1765     */
1766    private void onAppUpPressed() {
1767        if (mLaunchedFromEmail) {
1768            // If this was started from Gmail, simply treat app up as the system back button, so
1769            // that the last view is restored.
1770            onBackPressed();
1771            return;
1772        }
1773
1774        // Fire the main activity to ensure it launches the "top" screen of mail.
1775        // Since the main Activity is singleTask, it should revive that task if it was already
1776        // started.
1777        final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
1778        mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
1779                Intent.FLAG_ACTIVITY_TASK_ON_HOME);
1780        startActivity(mailIntent);
1781        finish();
1782    }
1783
1784    private void doSend() {
1785        sendOrSaveWithSanityChecks(false, true, false, false);
1786    }
1787
1788    private void doSave(boolean showToast) {
1789        sendOrSaveWithSanityChecks(true, showToast, false, false);
1790    }
1791
1792    @VisibleForTesting
1793    public interface SendOrSaveCallback {
1794        public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
1795        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
1796        public Message getMessage();
1797        public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
1798    }
1799
1800    @VisibleForTesting
1801    public static class SendOrSaveTask implements Runnable {
1802        private final Context mContext;
1803        @VisibleForTesting
1804        public final SendOrSaveCallback mSendOrSaveCallback;
1805        @VisibleForTesting
1806        public final SendOrSaveMessage mSendOrSaveMessage;
1807        private ReplyFromAccount mExistingDraftAccount;
1808
1809        public SendOrSaveTask(Context context, SendOrSaveMessage message,
1810                SendOrSaveCallback callback, ReplyFromAccount draftAccount) {
1811            mContext = context;
1812            mSendOrSaveCallback = callback;
1813            mSendOrSaveMessage = message;
1814            mExistingDraftAccount = draftAccount;
1815        }
1816
1817        @Override
1818        public void run() {
1819            final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
1820
1821            final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
1822            Message message = mSendOrSaveCallback.getMessage();
1823            long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
1824            // If a previous draft has been saved, in an account that is different
1825            // than what the user wants to send from, remove the old draft, and treat this
1826            // as a new message
1827            if (mExistingDraftAccount != null
1828                    && !selectedAccount.account.uri.equals(mExistingDraftAccount.account.uri)) {
1829                if (messageId != UIProvider.INVALID_MESSAGE_ID) {
1830                    ContentResolver resolver = mContext.getContentResolver();
1831                    ContentValues values = new ContentValues();
1832                    values.put(BaseColumns._ID, messageId);
1833                    if (mExistingDraftAccount.account.expungeMessageUri != null) {
1834                        new ContentProviderTask.UpdateTask()
1835                                .run(resolver, mExistingDraftAccount.account.expungeMessageUri,
1836                                        values, null, null);
1837                    } else {
1838                        // TODO(mindyp) delete the conversation.
1839                    }
1840                    // reset messageId to 0, so a new message will be created
1841                    messageId = UIProvider.INVALID_MESSAGE_ID;
1842                }
1843            }
1844
1845            final long messageIdToSave = messageId;
1846            sendOrSaveMessage(messageIdToSave, sendOrSaveMessage, selectedAccount, message);
1847
1848            if (!sendOrSaveMessage.mSave) {
1849                UIProvider.incrementRecipientsTimesContacted(mContext,
1850                        (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
1851                UIProvider.incrementRecipientsTimesContacted(mContext,
1852                        (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
1853                UIProvider.incrementRecipientsTimesContacted(mContext,
1854                        (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
1855            }
1856            mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
1857        }
1858
1859        /**
1860         * Send or Save a message.
1861         */
1862        private void sendOrSaveMessage(long messageIdToSave, SendOrSaveMessage sendOrSaveMessage,
1863                ReplyFromAccount selectedAccount, Message message) {
1864            final ContentResolver resolver = mContext.getContentResolver();
1865            final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
1866
1867            final String accountMethod = sendOrSaveMessage.mSave ?
1868                    UIProvider.AccountCallMethods.SAVE_MESSAGE :
1869                    UIProvider.AccountCallMethods.SEND_MESSAGE;
1870
1871            try {
1872                if (updateExistingMessage) {
1873                    sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
1874
1875                    final Bundle result = callAccountSendSaveMethod(resolver,
1876                            selectedAccount.account, accountMethod, sendOrSaveMessage);
1877                    if (result == null) {
1878                        // TODO(pwestbro): Once Email supports the call api, remove this block
1879                        // If null was returned, then the provider didn't handle the call method
1880                        final Uri updateUri = Uri.parse(sendOrSaveMessage.mSave ?
1881                                message.saveUri : message.sendUri);
1882                        resolver.update(updateUri, sendOrSaveMessage.mValues, null, null);
1883                    }
1884                } else {
1885                    final Uri messageUri;
1886                    final Bundle result = callAccountSendSaveMethod(resolver,
1887                            selectedAccount.account, accountMethod, sendOrSaveMessage);
1888                    if (result != null) {
1889                        // If a non-null value was returned, then the provider handled the call
1890                        // method
1891                        messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
1892                    } else {
1893                        // TODO(pwestbro): Once Email supports the call api, remove this block
1894                        messageUri = resolver.insert(
1895                                sendOrSaveMessage.mSave ? selectedAccount.account.saveDraftUri
1896                                        : selectedAccount.account.sendMessageUri,
1897                                sendOrSaveMessage.mValues);
1898                    }
1899                    if (sendOrSaveMessage.mSave && messageUri != null) {
1900                        final Cursor messageCursor = resolver.query(messageUri,
1901                                UIProvider.MESSAGE_PROJECTION, null, null, null);
1902                        if (messageCursor != null) {
1903                            try {
1904                                if (messageCursor.moveToFirst()) {
1905                                    // Broadcast notification that a new message has
1906                                    // been allocated
1907                                    mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
1908                                            new Message(messageCursor));
1909                                }
1910                            } finally {
1911                                messageCursor.close();
1912                            }
1913                        }
1914                    }
1915                }
1916            } finally {
1917                // Close any opened file descriptors
1918                closeOpenedAttachmentFds(sendOrSaveMessage);
1919            }
1920        }
1921
1922        private void closeOpenedAttachmentFds(SendOrSaveMessage sendOrSaveMessage) {
1923            final Bundle openedFds = sendOrSaveMessage.attachmentFds();
1924            if (openedFds != null) {
1925                final Set<String> keys = openedFds.keySet();
1926                for (String key : keys) {
1927                    final ParcelFileDescriptor fd = openedFds.getParcelable(key);
1928                    if (fd != null) {
1929                        try {
1930                            fd.close();
1931                        } catch (IOException e) {
1932                            // Do nothing
1933                        }
1934                    }
1935                }
1936            }
1937        }
1938
1939        /**
1940         * Use the {@link ContentResolver#call()} method to send or save the message.
1941         *
1942         * If this was successful, this method will return an non-null Bundle instance
1943         */
1944        private Bundle callAccountSendSaveMethod(ContentResolver resolver, Account account,
1945                String method, SendOrSaveMessage sendOrSaveMessage) {
1946            // Copy all of the values from the content values to the bundle
1947            final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
1948            final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
1949
1950            for (Entry<String, Object> entry : valueSet) {
1951                final Object entryValue = entry.getValue();
1952                final String key = entry.getKey();
1953                if (entryValue instanceof String) {
1954                    methodExtras.putString(key, (String)entryValue);
1955                } else if (entryValue instanceof Boolean) {
1956                    methodExtras.putBoolean(key, (Boolean)entryValue);
1957                } else if (entryValue instanceof Integer) {
1958                    methodExtras.putInt(key, (Integer)entryValue);
1959                } else if (entryValue instanceof Long) {
1960                    methodExtras.putLong(key, (Long)entryValue);
1961                } else {
1962                    LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
1963                            entryValue.getClass().getName());
1964                }
1965            }
1966
1967            // If the SendOrSaveMessage has some opened fds, add them to the bundle
1968            final Bundle fdMap = sendOrSaveMessage.attachmentFds();
1969            if (fdMap != null) {
1970                methodExtras.putParcelable(
1971                        UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
1972            }
1973
1974            return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
1975        }
1976    }
1977
1978    // Array of the outstanding send or save tasks.  Access is synchronized
1979    // with the object itself
1980    /* package for testing */
1981    @VisibleForTesting
1982    public ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
1983    // FIXME: this variable is never read. related to sRequestMessageIdMap.
1984    private int mRequestId;
1985    private String mSignature;
1986    private Account[] mAccounts;
1987
1988    @VisibleForTesting
1989    public static class SendOrSaveMessage {
1990        final ReplyFromAccount mAccount;
1991        final ContentValues mValues;
1992        final String mRefMessageId;
1993        @VisibleForTesting
1994        public final boolean mSave;
1995        final int mRequestId;
1996        private final Bundle mAttachmentFds;
1997
1998        public SendOrSaveMessage(Context context, ReplyFromAccount account, ContentValues values,
1999                String refMessageId, List<Attachment> attachments, boolean save) {
2000            mAccount = account;
2001            mValues = values;
2002            mRefMessageId = refMessageId;
2003            mSave = save;
2004            mRequestId = mValues.hashCode() ^ hashCode();
2005
2006            mAttachmentFds = initializeAttachmentFds(context, attachments);
2007        }
2008
2009        int requestId() {
2010            return mRequestId;
2011        }
2012
2013        Bundle attachmentFds() {
2014            return mAttachmentFds;
2015        }
2016
2017        /**
2018         * Opens {@link ParcelFileDescriptor} for each of the attachments.  This method must be
2019         * called before the ComposeActivity finishes.
2020         * Note: The caller is responsible for closing these file descriptors.
2021         */
2022        private Bundle initializeAttachmentFds(Context context, List<Attachment> attachments) {
2023            if (attachments == null || attachments.size() == 0) {
2024                return null;
2025            }
2026
2027            final Bundle result = new Bundle(attachments.size());
2028            final ContentResolver resolver = context.getContentResolver();
2029
2030            for (Attachment attachment : attachments) {
2031                if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2032                    continue;
2033                }
2034
2035                ParcelFileDescriptor fileDescriptor;
2036                try {
2037                    fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2038                } catch (FileNotFoundException e) {
2039                    LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2040                    fileDescriptor = null;
2041                }
2042
2043                if (fileDescriptor != null) {
2044                    result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2045                }
2046            }
2047
2048            return result;
2049        }
2050    }
2051
2052    /**
2053     * Get the to recipients.
2054     */
2055    public String[] getToAddresses() {
2056        return getAddressesFromList(mTo);
2057    }
2058
2059    /**
2060     * Get the cc recipients.
2061     */
2062    public String[] getCcAddresses() {
2063        return getAddressesFromList(mCc);
2064    }
2065
2066    /**
2067     * Get the bcc recipients.
2068     */
2069    public String[] getBccAddresses() {
2070        return getAddressesFromList(mBcc);
2071    }
2072
2073    public String[] getAddressesFromList(RecipientEditTextView list) {
2074        if (list == null) {
2075            return new String[0];
2076        }
2077        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2078        int count = tokens.length;
2079        String[] result = new String[count];
2080        for (int i = 0; i < count; i++) {
2081            result[i] = tokens[i].toString();
2082        }
2083        return result;
2084    }
2085
2086    /**
2087     * Check for invalid email addresses.
2088     * @param to String array of email addresses to check.
2089     * @param wrongEmailsOut Emails addresses that were invalid.
2090     */
2091    public void checkInvalidEmails(String[] to, List<String> wrongEmailsOut) {
2092        if (mValidator == null) {
2093            return;
2094        }
2095        for (String email : to) {
2096            if (!mValidator.isValid(email)) {
2097                wrongEmailsOut.add(email);
2098            }
2099        }
2100    }
2101
2102    /**
2103     * Show an error because the user has entered an invalid recipient.
2104     * @param message
2105     */
2106    public void showRecipientErrorDialog(String message) {
2107        // Only 1 invalid recipients error dialog should be allowed up at a
2108        // time.
2109        if (mRecipientErrorDialog != null) {
2110            mRecipientErrorDialog.dismiss();
2111        }
2112        mRecipientErrorDialog = new AlertDialog.Builder(this).setMessage(message).setTitle(
2113                R.string.recipient_error_dialog_title)
2114                .setIconAttribute(android.R.attr.alertDialogIcon)
2115                .setPositiveButton(
2116                        R.string.ok, new Dialog.OnClickListener() {
2117                            @Override
2118                            public void onClick(DialogInterface dialog, int which) {
2119                                // after the user dismisses the recipient error
2120                                // dialog we want to make sure to refocus the
2121                                // recipient to field so they can fix the issue
2122                                // easily
2123                                if (mTo != null) {
2124                                    mTo.requestFocus();
2125                                }
2126                                mRecipientErrorDialog = null;
2127                            }
2128                        }).show();
2129    }
2130
2131    /**
2132     * Update the state of the UI based on whether or not the current draft
2133     * needs to be saved and the message is not empty.
2134     */
2135    public void updateSaveUi() {
2136        if (mSave != null) {
2137            mSave.setEnabled((shouldSave() && !isBlank()));
2138        }
2139    }
2140
2141    /**
2142     * Returns true if we need to save the current draft.
2143     */
2144    private boolean shouldSave() {
2145        synchronized (mDraftLock) {
2146            // The message should only be saved if:
2147            // It hasn't been sent AND
2148            // Some text has been added to the message OR
2149            // an attachment has been added or removed
2150            // AND there is actually something in the draft to save.
2151            return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
2152                    && !isBlank();
2153        }
2154    }
2155
2156    /**
2157     * Check if all fields are blank.
2158     * @return boolean
2159     */
2160    public boolean isBlank() {
2161        return mSubject.getText().length() == 0
2162                && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2163                        mBodyView.getText().toString()) == 0)
2164                && mTo.length() == 0
2165                && mCc.length() == 0 && mBcc.length() == 0
2166                && mAttachmentsView.getAttachments().size() == 0;
2167    }
2168
2169    @VisibleForTesting
2170    protected int getSignatureStartPosition(String signature, String bodyText) {
2171        int startPos = -1;
2172
2173        if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2174            return startPos;
2175        }
2176
2177        int bodyLength = bodyText.length();
2178        int signatureLength = signature.length();
2179        String printableVersion = convertToPrintableSignature(signature);
2180        int printableLength = printableVersion.length();
2181
2182        if (bodyLength >= printableLength
2183                && bodyText.substring(bodyLength - printableLength)
2184                .equals(printableVersion)) {
2185            startPos = bodyLength - printableLength;
2186        } else if (bodyLength >= signatureLength
2187                && bodyText.substring(bodyLength - signatureLength)
2188                .equals(signature)) {
2189            startPos = bodyLength - signatureLength;
2190        }
2191        return startPos;
2192    }
2193
2194    /**
2195     * Allows any changes made by the user to be ignored. Called when the user
2196     * decides to discard a draft.
2197     */
2198    private void discardChanges() {
2199        mTextChanged = false;
2200        mAttachmentsChanged = false;
2201        mReplyFromChanged = false;
2202    }
2203
2204    /**
2205     * @param body
2206     * @param save
2207     * @param showToast
2208     * @return Whether the send or save succeeded.
2209     */
2210    protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
2211            final boolean orientationChanged, final boolean autoSend) {
2212        if (mAccounts == null || mAccount == null) {
2213            Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
2214            if (autoSend) {
2215                finish();
2216            }
2217            return false;
2218        }
2219
2220        String[] to, cc, bcc;
2221        Editable body = mBodyView.getEditableText();
2222        if (orientationChanged) {
2223            to = cc = bcc = new String[0];
2224        } else {
2225            to = getToAddresses();
2226            cc = getCcAddresses();
2227            bcc = getBccAddresses();
2228        }
2229
2230        // Don't let the user send to nobody (but it's okay to save a message
2231        // with no recipients)
2232        if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2233            showRecipientErrorDialog(getString(R.string.recipient_needed));
2234            return false;
2235        }
2236
2237        List<String> wrongEmails = new ArrayList<String>();
2238        if (!save) {
2239            checkInvalidEmails(to, wrongEmails);
2240            checkInvalidEmails(cc, wrongEmails);
2241            checkInvalidEmails(bcc, wrongEmails);
2242        }
2243
2244        // Don't let the user send an email with invalid recipients
2245        if (wrongEmails.size() > 0) {
2246            String errorText = String.format(getString(R.string.invalid_recipient),
2247                    wrongEmails.get(0));
2248            showRecipientErrorDialog(errorText);
2249            return false;
2250        }
2251
2252        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
2253            @Override
2254            public void onClick(DialogInterface dialog, int which) {
2255                sendOrSave(mBodyView.getEditableText(), save, showToast, orientationChanged);
2256            }
2257        };
2258
2259        // Show a warning before sending only if there are no attachments.
2260        if (!save) {
2261            if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2262                boolean warnAboutEmptySubject = isSubjectEmpty();
2263                boolean emptyBody = TextUtils.getTrimmedLength(body) == 0;
2264
2265                // A warning about an empty body may not be warranted when
2266                // forwarding mails, since a common use case is to forward
2267                // quoted text and not append any more text.
2268                boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
2269
2270                // When we bring up a dialog warning the user about a send,
2271                // assume that they accept sending the message. If they do not,
2272                // the dialog listener is required to enable sending again.
2273                if (warnAboutEmptySubject) {
2274                    showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, listener);
2275                    return true;
2276                }
2277
2278                if (warnAboutEmptyBody) {
2279                    showSendConfirmDialog(R.string.confirm_send_message_with_no_body, listener);
2280                    return true;
2281                }
2282            }
2283            // Ask for confirmation to send (if always required)
2284            if (showSendConfirmation()) {
2285                showSendConfirmDialog(R.string.confirm_send_message, listener);
2286                return true;
2287            }
2288        }
2289
2290        sendOrSave(body, save, showToast, false);
2291        return true;
2292    }
2293
2294    /**
2295     * Returns a boolean indicating whether warnings should be shown for empty
2296     * subject and body fields
2297     *
2298     * @return True if a warning should be shown for empty text fields
2299     */
2300    protected boolean showEmptyTextWarnings() {
2301        return mAttachmentsView.getAttachments().size() == 0;
2302    }
2303
2304    /**
2305     * Returns a boolean indicating whether the user should confirm each send
2306     *
2307     * @return True if a warning should be on each send
2308     */
2309    protected boolean showSendConfirmation() {
2310        return mCachedSettings != null ? mCachedSettings.confirmSend : false;
2311    }
2312
2313    private void showSendConfirmDialog(int messageId, DialogInterface.OnClickListener listener) {
2314        if (mSendConfirmDialog != null) {
2315            mSendConfirmDialog.dismiss();
2316            mSendConfirmDialog = null;
2317        }
2318        mSendConfirmDialog = new AlertDialog.Builder(this).setMessage(messageId)
2319                .setTitle(R.string.confirm_send_title)
2320                .setIconAttribute(android.R.attr.alertDialogIcon)
2321                .setPositiveButton(R.string.send, listener)
2322                .setNegativeButton(R.string.cancel, this)
2323                .show();
2324    }
2325
2326    /**
2327     * Returns whether the ComposeArea believes there is any text in the body of
2328     * the composition. TODO: When ComposeArea controls the Body as well, add
2329     * that here.
2330     */
2331    public boolean isBodyEmpty() {
2332        return !mQuotedTextView.isTextIncluded();
2333    }
2334
2335    /**
2336     * Test to see if the subject is empty.
2337     *
2338     * @return boolean.
2339     */
2340    // TODO: this will likely go away when composeArea.focus() is implemented
2341    // after all the widget control is moved over.
2342    public boolean isSubjectEmpty() {
2343        return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
2344    }
2345
2346    /* package */
2347    static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
2348            Message message, final Message refMessage, Spanned body, final CharSequence quotedText,
2349            SendOrSaveCallback callback, Handler handler, boolean save, int composeMode,
2350            ReplyFromAccount draftAccount) {
2351        ContentValues values = new ContentValues();
2352
2353        String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
2354
2355        MessageModification.putToAddresses(values, message.getToAddresses());
2356        MessageModification.putCcAddresses(values, message.getCcAddresses());
2357        MessageModification.putBccAddresses(values, message.getBccAddresses());
2358
2359        MessageModification.putCustomFromAddress(values, message.getFrom());
2360
2361        MessageModification.putSubject(values, message.subject);
2362        String htmlBody = Html.toHtml(new SpannableString(body.toString()));
2363
2364        boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
2365        StringBuilder fullBody = new StringBuilder(htmlBody);
2366        if (includeQuotedText) {
2367            // HTML gets converted to text for now
2368            final String text = quotedText.toString();
2369            if (QuotedTextView.containsQuotedText(text)) {
2370                int pos = QuotedTextView.getQuotedTextOffset(text);
2371                final int quoteStartPos = fullBody.length() + pos;
2372                fullBody.append(text);
2373                MessageModification.putQuoteStartPos(values, quoteStartPos);
2374                MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
2375                MessageModification.putAppendRefMessageContent(values, includeQuotedText);
2376            } else {
2377                LogUtils.w(LOG_TAG, "Couldn't find quoted text");
2378                // This shouldn't happen, but just use what we have,
2379                // and don't do server-side expansion
2380                fullBody.append(text);
2381            }
2382        }
2383        int draftType = getDraftType(composeMode);
2384        MessageModification.putDraftType(values, draftType);
2385        if (refMessage != null) {
2386            if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
2387                MessageModification.putBodyHtml(values, fullBody.toString());
2388            }
2389            if (!TextUtils.isEmpty(refMessage.bodyText)) {
2390                MessageModification.putBody(values,
2391                        Utils.convertHtmlToPlainText(fullBody.toString()).toString());
2392            }
2393        } else {
2394            MessageModification.putBodyHtml(values, fullBody.toString());
2395            MessageModification.putBody(values, Utils.convertHtmlToPlainText(fullBody.toString())
2396                    .toString());
2397        }
2398        MessageModification.putAttachments(values, message.getAttachments());
2399        if (!TextUtils.isEmpty(refMessageId)) {
2400            MessageModification.putRefMessageId(values, refMessageId);
2401        }
2402        SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, replyFromAccount,
2403                values, refMessageId, message.getAttachments(), save);
2404        SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback,
2405                draftAccount);
2406
2407        callback.initializeSendOrSave(sendOrSaveTask);
2408        // Do the send/save action on the specified handler to avoid possible
2409        // ANRs
2410        handler.post(sendOrSaveTask);
2411
2412        return sendOrSaveMessage.requestId();
2413    }
2414
2415    private static int getDraftType(int mode) {
2416        int draftType = -1;
2417        switch (mode) {
2418            case ComposeActivity.COMPOSE:
2419                draftType = DraftType.COMPOSE;
2420                break;
2421            case ComposeActivity.REPLY:
2422                draftType = DraftType.REPLY;
2423                break;
2424            case ComposeActivity.REPLY_ALL:
2425                draftType = DraftType.REPLY_ALL;
2426                break;
2427            case ComposeActivity.FORWARD:
2428                draftType = DraftType.FORWARD;
2429                break;
2430        }
2431        return draftType;
2432    }
2433
2434    private void sendOrSave(Spanned body, boolean save, boolean showToast,
2435            boolean orientationChanged) {
2436        // Check if user is a monkey. Monkeys can compose and hit send
2437        // button but are not allowed to send anything off the device.
2438        if (ActivityManager.isUserAMonkey()) {
2439            return;
2440        }
2441
2442        String[] to, cc, bcc;
2443        if (orientationChanged) {
2444            to = cc = bcc = new String[0];
2445        } else {
2446            to = getToAddresses();
2447            cc = getCcAddresses();
2448            bcc = getBccAddresses();
2449        }
2450
2451        SendOrSaveCallback callback = new SendOrSaveCallback() {
2452            // FIXME: unused
2453            private int mRestoredRequestId;
2454
2455            @Override
2456            public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
2457                synchronized (mActiveTasks) {
2458                    int numTasks = mActiveTasks.size();
2459                    if (numTasks == 0) {
2460                        // Start service so we won't be killed if this app is
2461                        // put in the background.
2462                        startService(new Intent(ComposeActivity.this, EmptyService.class));
2463                    }
2464
2465                    mActiveTasks.add(sendOrSaveTask);
2466                }
2467                if (sTestSendOrSaveCallback != null) {
2468                    sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
2469                }
2470            }
2471
2472            @Override
2473            public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
2474                    Message message) {
2475                synchronized (mDraftLock) {
2476                    mDraftAccount = sendOrSaveMessage.mAccount;
2477                    mDraftId = message.id;
2478                    mDraft = message;
2479                    if (sRequestMessageIdMap != null) {
2480                        sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
2481                    }
2482                    // Cache request message map, in case the process is killed
2483                    saveRequestMap();
2484                }
2485                if (sTestSendOrSaveCallback != null) {
2486                    sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
2487                }
2488            }
2489
2490            @Override
2491            public Message getMessage() {
2492                synchronized (mDraftLock) {
2493                    return mDraft;
2494                }
2495            }
2496
2497            @Override
2498            public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
2499                // Update the last sent from account.
2500                if (mAccount != null) {
2501                    MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
2502                }
2503                if (success) {
2504                    // Successfully sent or saved so reset change markers
2505                    discardChanges();
2506                } else {
2507                    // A failure happened with saving/sending the draft
2508                    // TODO(pwestbro): add a better string that should be used
2509                    // when failing to send or save
2510                    Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
2511                            .show();
2512                }
2513
2514                int numTasks;
2515                synchronized (mActiveTasks) {
2516                    // Remove the task from the list of active tasks
2517                    mActiveTasks.remove(task);
2518                    numTasks = mActiveTasks.size();
2519                }
2520
2521                if (numTasks == 0) {
2522                    // Stop service so we can be killed.
2523                    stopService(new Intent(ComposeActivity.this, EmptyService.class));
2524                }
2525                if (sTestSendOrSaveCallback != null) {
2526                    sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
2527                }
2528            }
2529        };
2530
2531        // Get the selected account if the from spinner has been setup.
2532        ReplyFromAccount selectedAccount = mReplyFromAccount;
2533        String fromAddress = selectedAccount.name;
2534        if (selectedAccount == null || fromAddress == null) {
2535            // We don't have either the selected account or from address,
2536            // use mAccount.
2537            selectedAccount = mReplyFromAccount;
2538            fromAddress = mAccount.name;
2539        }
2540
2541        if (mSendSaveTaskHandler == null) {
2542            HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
2543            handlerThread.start();
2544
2545            mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
2546        }
2547
2548        Message msg = createMessage(mReplyFromAccount, getMode());
2549        mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body,
2550                mQuotedTextView.getQuotedTextIfIncluded(), callback,
2551                mSendSaveTaskHandler, save, mComposeMode, mDraftAccount);
2552
2553        if (mRecipient != null && mRecipient.equals(mAccount.name)) {
2554            mRecipient = selectedAccount.name;
2555        }
2556        setAccount(selectedAccount.account);
2557
2558        // Don't display the toast if the user is just changing the orientation,
2559        // but we still need to save the draft to the cursor because this is how we restore
2560        // the attachments when the configuration change completes.
2561        if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
2562            Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
2563                    Toast.LENGTH_LONG).show();
2564        }
2565
2566        // Need to update variables here because the send or save completes
2567        // asynchronously even though the toast shows right away.
2568        discardChanges();
2569        updateSaveUi();
2570
2571        // If we are sending, finish the activity
2572        if (!save) {
2573            finish();
2574        }
2575    }
2576
2577    /**
2578     * Save the state of the request messageid map. This allows for the Gmail
2579     * process to be killed, but and still allow for ComposeActivity instances
2580     * to be recreated correctly.
2581     */
2582    private void saveRequestMap() {
2583        // TODO: store the request map in user preferences.
2584    }
2585
2586    private void doAttach(String type) {
2587        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2588        i.addCategory(Intent.CATEGORY_OPENABLE);
2589        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2590        i.setType(type);
2591        mAddingAttachment = true;
2592        startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2593                RESULT_PICK_ATTACHMENT);
2594    }
2595
2596    private void showCcBccViews() {
2597        mCcBccView.show(true, true, true);
2598        if (mCcBccButton != null) {
2599            mCcBccButton.setVisibility(View.INVISIBLE);
2600        }
2601    }
2602
2603    @Override
2604    public boolean onNavigationItemSelected(int position, long itemId) {
2605        int initialComposeMode = mComposeMode;
2606        if (position == ComposeActivity.REPLY) {
2607            mComposeMode = ComposeActivity.REPLY;
2608        } else if (position == ComposeActivity.REPLY_ALL) {
2609            mComposeMode = ComposeActivity.REPLY_ALL;
2610        } else if (position == ComposeActivity.FORWARD) {
2611            mComposeMode = ComposeActivity.FORWARD;
2612        }
2613        clearChangeListeners();
2614        if (initialComposeMode != mComposeMode) {
2615            resetMessageForModeChange();
2616            if (mDraft == null && mRefMessage != null) {
2617                setFieldsFromRefMessage(mComposeMode, mAccount.name);
2618            }
2619            boolean showCc = false;
2620            boolean showBcc = false;
2621            if (mDraft != null) {
2622                // Following desktop behavior, if the user has added a BCC
2623                // field to a draft, we show it regardless of compose mode.
2624                showBcc = !TextUtils.isEmpty(mDraft.getBcc());
2625                // Use the draft to determine what to populate.
2626                // If the Bcc field is showing, show the Cc field whether it is populated or not.
2627                showCc = showBcc
2628                        || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
2629            } else if (mRefMessage != null) {
2630                showCc = !TextUtils.isEmpty(mCc.getText());
2631            }
2632            mCcBccView.show(false, showCc, showBcc);
2633        }
2634        updateHideOrShowCcBcc();
2635        initChangeListeners();
2636        return true;
2637    }
2638
2639    @VisibleForTesting
2640    protected void resetMessageForModeChange() {
2641        // When switching between reply, reply all, forward,
2642        // follow the behavior of webview.
2643        // The contents of the following fields are cleared
2644        // so that they can be populated directly from the
2645        // ref message:
2646        // 1) Any recipient fields
2647        // 2) The subject
2648        mTo.setText("");
2649        mCc.setText("");
2650        mBcc.setText("");
2651        // Any edits to the subject are replaced with the original subject.
2652        mSubject.setText("");
2653
2654        // Any changes to the contents of the following fields are kept:
2655        // 1) Body
2656        // 2) Attachments
2657        // If the user made changes to attachments, keep their changes.
2658        if (!mAttachmentsChanged) {
2659            mAttachmentsView.deleteAllAttachments();
2660        }
2661    }
2662
2663    private class ComposeModeAdapter extends ArrayAdapter<String> {
2664
2665        private LayoutInflater mInflater;
2666
2667        public ComposeModeAdapter(Context context) {
2668            super(context, R.layout.compose_mode_item, R.id.mode, getResources()
2669                    .getStringArray(R.array.compose_modes));
2670        }
2671
2672        private LayoutInflater getInflater() {
2673            if (mInflater == null) {
2674                mInflater = LayoutInflater.from(getContext());
2675            }
2676            return mInflater;
2677        }
2678
2679        @Override
2680        public View getView(int position, View convertView, ViewGroup parent) {
2681            if (convertView == null) {
2682                convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
2683            }
2684            ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
2685            return super.getView(position, convertView, parent);
2686        }
2687    }
2688
2689    @Override
2690    public void onRespondInline(String text) {
2691        appendToBody(text, false);
2692        mQuotedTextView.setUpperDividerVisible(false);
2693        mTo.requestFocus();
2694    }
2695
2696    /**
2697     * Append text to the body of the message. If there is no existing body
2698     * text, just sets the body to text.
2699     *
2700     * @param text
2701     * @param withSignature True to append a signature.
2702     */
2703    public void appendToBody(CharSequence text, boolean withSignature) {
2704        Editable bodyText = mBodyView.getEditableText();
2705        if (bodyText != null && bodyText.length() > 0) {
2706            bodyText.append(text);
2707        } else {
2708            setBody(text, withSignature);
2709        }
2710    }
2711
2712    /**
2713     * Set the body of the message.
2714     *
2715     * @param text
2716     * @param withSignature True to append a signature.
2717     */
2718    public void setBody(CharSequence text, boolean withSignature) {
2719        mBodyView.setText(text);
2720        if (withSignature) {
2721            appendSignature();
2722        }
2723    }
2724
2725    private void appendSignature() {
2726        String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
2727        boolean hasFocus = mBodyView.hasFocus();
2728        int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
2729        if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
2730            mSignature = newSignature;
2731            if (!TextUtils.isEmpty(mSignature)) {
2732                // Appending a signature does not count as changing text.
2733                mBodyView.removeTextChangedListener(this);
2734                mBodyView.append(convertToPrintableSignature(mSignature));
2735                mBodyView.addTextChangedListener(this);
2736            }
2737            if (hasFocus) {
2738                focusBody();
2739            }
2740        }
2741    }
2742
2743    private String convertToPrintableSignature(String signature) {
2744        String signatureResource = getResources().getString(R.string.signature);
2745        if (signature == null) {
2746            signature = "";
2747        }
2748        return String.format(signatureResource, signature);
2749    }
2750
2751    @Override
2752    public void onAccountChanged() {
2753        mReplyFromAccount = mFromSpinner.getCurrentAccount();
2754        if (!mAccount.equals(mReplyFromAccount.account)) {
2755            // Clear a signature, if there was one.
2756            mBodyView.removeTextChangedListener(this);
2757            String oldSignature = mSignature;
2758            String bodyText = getBody().getText().toString();
2759            if (!TextUtils.isEmpty(oldSignature)) {
2760                int pos = getSignatureStartPosition(oldSignature, bodyText);
2761                if (pos > -1) {
2762                    mBodyView.setText(bodyText.substring(0, pos));
2763                }
2764            }
2765            setAccount(mReplyFromAccount.account);
2766            mBodyView.addTextChangedListener(this);
2767            // TODO: handle discarding attachments when switching accounts.
2768            // Only enable save for this draft if there is any other content
2769            // in the message.
2770            if (!isBlank()) {
2771                enableSave(true);
2772            }
2773            mReplyFromChanged = true;
2774            initRecipients();
2775        }
2776    }
2777
2778    public void enableSave(boolean enabled) {
2779        if (mSave != null) {
2780            mSave.setEnabled(enabled);
2781        }
2782    }
2783
2784    public void enableSend(boolean enabled) {
2785        if (mSend != null) {
2786            mSend.setEnabled(enabled);
2787        }
2788    }
2789
2790    /**
2791     * Handles button clicks from any error dialogs dealing with sending
2792     * a message.
2793     */
2794    @Override
2795    public void onClick(DialogInterface dialog, int which) {
2796        switch (which) {
2797            case DialogInterface.BUTTON_POSITIVE: {
2798                doDiscardWithoutConfirmation(true /* show toast */ );
2799                break;
2800            }
2801            case DialogInterface.BUTTON_NEGATIVE: {
2802                // If the user cancels the send, re-enable the send button.
2803                enableSend(true);
2804                break;
2805            }
2806        }
2807
2808    }
2809
2810    private void doDiscard() {
2811        new AlertDialog.Builder(this).setMessage(R.string.confirm_discard_text)
2812                .setPositiveButton(R.string.ok, this)
2813                .setNegativeButton(R.string.cancel, null)
2814                .create().show();
2815    }
2816    /**
2817     * Effectively discard the current message.
2818     *
2819     * This method is either invoked from the menu or from the dialog
2820     * once the user has confirmed that they want to discard the message.
2821     * @param showToast show "Message discarded" toast if true
2822     */
2823    private void doDiscardWithoutConfirmation(boolean showToast) {
2824        synchronized (mDraftLock) {
2825            if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
2826                ContentValues values = new ContentValues();
2827                values.put(BaseColumns._ID, mDraftId);
2828                if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
2829                    getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
2830                } else {
2831                    getContentResolver().delete(mDraft.uri, null, null);
2832                }
2833                // This is not strictly necessary (since we should not try to
2834                // save the draft after calling this) but it ensures that if we
2835                // do save again for some reason we make a new draft rather than
2836                // trying to resave an expunged draft.
2837                mDraftId = UIProvider.INVALID_MESSAGE_ID;
2838            }
2839        }
2840
2841        if (showToast) {
2842            // Display a toast to let the user know
2843            Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
2844        }
2845
2846        // This prevents the draft from being saved in onPause().
2847        discardChanges();
2848        finish();
2849    }
2850
2851    private void saveIfNeeded() {
2852        if (mAccount == null) {
2853            // We have not chosen an account yet so there's no way that we can save. This is ok,
2854            // though, since we are saving our state before AccountsActivity is activated. Thus, the
2855            // user has not interacted with us yet and there is no real state to save.
2856            return;
2857        }
2858
2859        if (shouldSave()) {
2860            doSave(!mAddingAttachment /* show toast */);
2861        }
2862    }
2863
2864    @Override
2865    public void onAttachmentDeleted() {
2866        mAttachmentsChanged = true;
2867        // If we are showing any attachments, make sure we have an upper
2868        // divider.
2869        mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
2870        updateSaveUi();
2871    }
2872
2873    @Override
2874    public void onAttachmentAdded() {
2875        mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
2876        mAttachmentsView.focusLastAttachment();
2877    }
2878
2879    /**
2880     * This is called any time one of our text fields changes.
2881     */
2882    @Override
2883    public void afterTextChanged(Editable s) {
2884        mTextChanged = true;
2885        updateSaveUi();
2886    }
2887
2888    @Override
2889    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2890        // Do nothing.
2891    }
2892
2893    @Override
2894    public void onTextChanged(CharSequence s, int start, int before, int count) {
2895        // Do nothing.
2896    }
2897
2898
2899    // There is a big difference between the text associated with an address changing
2900    // to add the display name or to format properly and a recipient being added or deleted.
2901    // Make sure we only notify of changes when a recipient has been added or deleted.
2902    private class RecipientTextWatcher implements TextWatcher {
2903        private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
2904
2905        private RecipientEditTextView mView;
2906
2907        private TextWatcher mListener;
2908
2909        public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
2910            mView = view;
2911            mListener = listener;
2912        }
2913
2914        @Override
2915        public void afterTextChanged(Editable s) {
2916            if (hasChanged()) {
2917                mListener.afterTextChanged(s);
2918            }
2919        }
2920
2921        private boolean hasChanged() {
2922            String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
2923            int totalCount = currRecips.length;
2924            int totalPrevCount = 0;
2925            for (Entry<String, Integer> entry : mContent.entrySet()) {
2926                totalPrevCount += entry.getValue();
2927            }
2928            if (totalCount != totalPrevCount) {
2929                return true;
2930            }
2931
2932            for (String recip : currRecips) {
2933                if (!mContent.containsKey(recip)) {
2934                    return true;
2935                } else {
2936                    int count = mContent.get(recip) - 1;
2937                    if (count < 0) {
2938                        return true;
2939                    } else {
2940                        mContent.put(recip, count);
2941                    }
2942                }
2943            }
2944            return false;
2945        }
2946
2947        private String[] tokenizeRecips(String[] recips) {
2948            // Tokenize them all and put them in the list.
2949            String[] recipAddresses = new String[recips.length];
2950            for (int i = 0; i < recips.length; i++) {
2951                recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
2952            }
2953            return recipAddresses;
2954        }
2955
2956        @Override
2957        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2958            String[] recips = tokenizeRecips(getAddressesFromList(mView));
2959            for (String recip : recips) {
2960                if (!mContent.containsKey(recip)) {
2961                    mContent.put(recip, 1);
2962                } else {
2963                    mContent.put(recip, (mContent.get(recip)) + 1);
2964                }
2965            }
2966        }
2967
2968        @Override
2969        public void onTextChanged(CharSequence s, int start, int before, int count) {
2970            // Do nothing.
2971        }
2972    }
2973
2974    public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
2975        if (sTestSendOrSaveCallback != null && testCallback != null) {
2976            throw new IllegalStateException("Attempting to register more than one test callback");
2977        }
2978        sTestSendOrSaveCallback = testCallback;
2979    }
2980
2981    @VisibleForTesting
2982    protected ArrayList<Attachment> getAttachments() {
2983        return mAttachmentsView.getAttachments();
2984    }
2985
2986    @Override
2987    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
2988        switch (id) {
2989            case REFERENCE_MESSAGE_LOADER:
2990                return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
2991                        null, null);
2992            case LOADER_ACCOUNT_CURSOR:
2993                return new CursorLoader(this, MailAppProvider.getAccountsUri(),
2994                        UIProvider.ACCOUNTS_PROJECTION, null, null, null);
2995        }
2996        return null;
2997    }
2998
2999    @Override
3000    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
3001        int id = loader.getId();
3002        switch (id) {
3003            case REFERENCE_MESSAGE_LOADER:
3004                if (data != null && data.moveToFirst()) {
3005                    mRefMessage = new Message(data);
3006                    // We set these based on EXTRA_TO.
3007                    mRefMessage.setTo(null);
3008                    mRefMessage.setFrom(null);
3009                    Intent intent = getIntent();
3010                    int action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
3011                    initFromRefMessage(action, mAccount.name);
3012                    finishSetup(action, intent, null, true);
3013                    if (action != FORWARD) {
3014                        String to = intent.getStringExtra(EXTRA_TO);
3015                        if (!TextUtils.isEmpty(to)) {
3016                            clearChangeListeners();
3017                            mTo.append(to);
3018                            initChangeListeners();
3019                        }
3020                    }
3021                } else {
3022                    finish();
3023                }
3024                break;
3025            case LOADER_ACCOUNT_CURSOR:
3026                if (data != null && data.moveToFirst()) {
3027                    // there are accounts now!
3028                    Account account;
3029                    final ArrayList<Account> accounts = new ArrayList<Account>();
3030                    final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
3031                    do {
3032                        account = new Account(data);
3033                        if (account.isAccountReady()) {
3034                            initializedAccounts.add(account);
3035                        }
3036                        accounts.add(account);
3037                    } while (data.moveToNext());
3038                    if (initializedAccounts.size() > 0) {
3039                        findViewById(R.id.wait).setVisibility(View.GONE);
3040                        getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3041                        findViewById(R.id.compose).setVisibility(View.VISIBLE);
3042                        mAccounts = initializedAccounts.toArray(
3043                                new Account[initializedAccounts.size()]);
3044
3045                        finishCreate();
3046                        invalidateOptionsMenu();
3047                    } else {
3048                        // Show "waiting"
3049                        account = accounts.size() > 0 ? accounts.get(0) : null;
3050                        showWaitFragment(account);
3051                    }
3052                }
3053                break;
3054        }
3055    }
3056
3057    private void showWaitFragment(Account account) {
3058        WaitFragment fragment = getWaitFragment();
3059        if (fragment != null) {
3060            fragment.updateAccount(account);
3061        } else {
3062            findViewById(R.id.wait).setVisibility(View.VISIBLE);
3063            replaceFragment(WaitFragment.newInstance(account, true),
3064                    FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3065        }
3066    }
3067
3068    private WaitFragment getWaitFragment() {
3069        return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3070    }
3071
3072    private int replaceFragment(Fragment fragment, int transition, String tag) {
3073        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
3074        fragmentTransaction.addToBackStack(null);
3075        fragmentTransaction.setTransition(transition);
3076        fragmentTransaction.replace(R.id.wait, fragment, tag);
3077        final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3078        return transactionId;
3079    }
3080
3081    @Override
3082    public void onLoaderReset(Loader<Cursor> arg0) {
3083        // Do nothing.
3084    }
3085}
3086