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