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